ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • AWS boto3 핵심 가이드(설치부터 S3·EC2 제어까지)-고슴도치 군단
    카테고리 없음 2026. 5. 8. 15:59

    boto3 개요

    boto3는 파이썬에서 AWS 서비스를 프로그래밍 방식으로 제어할 수 있는 공식 SDK임

    S3 파일 업로드, EC2 인스턴스 시작·중지, Lambda 호출 등 AWS의 거의 모든 서비스를 파이썬 코드로 자동화할 수 있음

    수동으로 AWS 콘솔에서 반복 작업하던 일을 boto3로 스크립트화하면 시간을 대폭 절약하고 실수를 줄일 수 있음



    설치 및 환경 설정

    boto3는 pip으로 간단히 설치할 수 있음

    가상환경 활성화 후 설치하면 프로젝트 의존성을 깔끔하게 관리할 수 있음

    # 가상환경 생성 및 활성화 (선택사항이지만 권장)
    python -m venv .venv
    source .venv/bin/activate  # Windows: .venv\Scripts\activate
    
    # boto3 설치
    pip install boto3

    설치 후 import boto3가 오류 없이 실행되면 준비 완료임



    AWS 인증 구성

    boto3는 여러 가지 인증 방식을 지원하며, 가장 일반적인 방법은 AWS CLI 자격 증명 파일을 사용하는 것임

    aws configure 명령어로 Access Key, Secret Key, 리전을 설정하면 boto3가 자동으로 인식함

    aws configure
    # AWS Access Key ID: <your-access-key>
    # AWS Secret Access Key: <your-secret-key>
    # Default region name: ap-northeast-2
    # Default output format: json

    코드 내에서 자격 증명을 하드코딩하는 방식은 보안 위험이 크므로 반드시 피해야 함

    EC2·Lambda 같은 AWS 환경에서 실행할 때는 IAM Role을 인스턴스에 부여하는 방식이 가장 안전하고 권장됨



    S3 파일 업로드·다운로드

    S3는 boto3에서 가장 많이 사용되는 서비스 중 하나임

    boto3.client('s3')로 클라이언트를 생성한 뒤 파일을 업로드·다운로드하거나 버킷 내 객체 목록을 조회할 수 있음

    import boto3
    
    s3 = boto3.client('s3', region_name='ap-northeast-2')
    
    # 파일 업로드
    s3.upload_file('local_file.txt', 'my-bucket', 'remote/path/file.txt')
    
    # 파일 다운로드
    s3.download_file('my-bucket', 'remote/path/file.txt', 'downloaded.txt')
    
    # 버킷 내 파일 목록 조회
    response = s3.list_objects_v2(Bucket='my-bucket', Prefix='remote/')
    for obj in response.get('Contents', []):
        print(obj['Key'], obj['Size'])

    list_objects_v2는 최대 1000개까지만 반환하므로 파일이 많은 버킷에서는 paginator를 사용해야 한다는 점에 주의해야 함

    # 1000개 이상 파일이 있을 때 — paginator 사용
    paginator = s3.get_paginator('list_objects_v2')
    for page in paginator.paginate(Bucket='my-bucket'):
        for obj in page.get('Contents', []):
            print(obj['Key'])


    EC2 인스턴스 제어

    boto3로 EC2 인스턴스를 시작·중지하고 상태를 조회하는 작업을 자동화할 수 있음

    특정 태그가 붙은 인스턴스를 필터링해서 일괄 제어하는 패턴이 실무에서 자주 사용됨

    import boto3
    
    ec2 = boto3.client('ec2', region_name='ap-northeast-2')
    
    # 태그 기준으로 인스턴스 목록 조회
    response = ec2.describe_instances(
        Filters=[{'Name': 'tag:Environment', 'Values': ['production']}]
    )
    
    for reservation in response['Reservations']:
        for instance in reservation['Instances']:
            instance_id = instance['InstanceId']
            state = instance['State']['Name']
            print(f"{instance_id}: {state}")
    
    # 인스턴스 중지
    ec2.stop_instances(InstanceIds=['i-0abc1234def56789'])
    
    # 인스턴스 시작
    ec2.start_instances(InstanceIds=['i-0abc1234def56789'])

    정기적인 인스턴스 스케줄링(예: 업무 시간 외 자동 중지)을 구현할 때 이 패턴이 핵심임

    중지·시작 후 인스턴스가 완전히 특정 상태에 도달할 때까지 대기해야 하는 경우 waiter를 활용하면 폴링 코드를 직접 작성하지 않아도 됨

    # 인스턴스가 완전히 중지될 때까지 대기
    waiter = ec2.get_waiter('instance_stopped')
    waiter.wait(InstanceIds=['i-0abc1234def56789'])
    print("인스턴스 중지 완료")


    client vs resource 인터페이스 비교

    boto3에는 clientresource 두 가지 인터페이스가 있음

    client는 AWS API를 그대로 노출하며 모든 서비스를 지원하고, resource는 객체지향 방식으로 더 직관적인 코드를 작성할 수 있게 해줌

    import boto3
    
    # client 방식 — 저수준 API, 모든 서비스 지원
    s3_client = boto3.client('s3')
    response = s3_client.list_buckets()
    for bucket in response['Buckets']:
        print(bucket['Name'])
    
    # resource 방식 — 객체지향 인터페이스 (S3, EC2 등 일부 서비스만 지원)
    s3_resource = boto3.resource('s3')
    bucket = s3_resource.Bucket('my-bucket')
    for obj in bucket.objects.all():
        print(obj.key)

    멀티 계정·멀티 리전 작업이 필요한 경우 boto3.Session()을 사용하면 자격 증명을 독립적으로 관리할 수 있음

    # 멀티 리전 또는 멀티 계정 작업 시 세션 활용
    session = boto3.Session(
        profile_name='my-aws-profile',  # ~/.aws/credentials의 프로파일명
        region_name='us-east-1'
    )
    s3 = session.client('s3')


    오류 처리와 예외 관리

    boto3에서 발생하는 오류는 botocore.exceptions.ClientError를 통해 처리할 수 있음

    AWS API 호출은 네트워크 문제나 서비스 한도 초과(ThrottlingException)로 실패할 수 있어 예외 처리가 필수임

    import boto3
    from botocore.exceptions import ClientError, NoCredentialsError
    
    s3 = boto3.client('s3')
    
    try:
        # 파일 존재 여부 확인
        s3.head_object(Bucket='my-bucket', Key='target_file.txt')
        print("파일이 존재함")
    except ClientError as e:
        error_code = e.response['Error']['Code']
        if error_code == '404':
            print("파일이 존재하지 않음")
        elif error_code == '403':
            print("접근 권한이 없음")
        else:
            raise
    except NoCredentialsError:
        print("AWS 자격 증명이 설정되지 않음")

    boto3는 기본적으로 일부 오류(503, ThrottlingException 등)에 대해 자동 재시도를 수행하며, Config 객체로 재시도 횟수와 방식을 커스터마이징할 수 있음

    from botocore.config import Config
    
    # 재시도 횟수와 모드 설정
    config = Config(retries={'max_attempts': 5, 'mode': 'adaptive'})
    s3 = boto3.client('s3', config=config)


    마무리

    boto3는 AWS 자동화의 핵심 도구로, 기본 개념만 익히면 S3·EC2·Lambda 등 다양한 서비스를 파이썬 코드로 제어할 수 있음

    실무에서는 환경 변수나 IAM Role을 통한 안전한 인증 구성, ClientError 기반 예외 처리, paginator를 활용한 대량 데이터 처리가 중요한 세 가지 기둥임

    더 복잡한 시나리오(대용량 파일 멀티파트 업로드, 이벤트 기반 자동화, Step Functions 연동)로 발전시키려면 transfer managerwaiter, 그리고 AWS Lambda와의 boto3 조합을 다음 단계로 학습하는 것을 권장함

Designed by Tistory.