import logging
import boto3
from botocore.exceptions import ClientError

 

  • logging: 파이썬의 로깅을 위한 패키지이다.
  • boto3: AWS의 파이썬 SDK이다. botocore를 사용자 관점에서 사용하기 쉽도록 추상화하였다.
  • botocore: boto3의 기반이 되는 패키지이다. low-level interface라고 명시한다.

아래 함수는 bucket을 생성하는 간단한 함수이다.

def create_bucket(bucket_name, region=None):
    """Create an S3 bucket in a specified region

    If a region is not specified, the bucket is created in the s3 defualt region (ap-northeast-2)

    Args:
        bucket_name (_type_): Bucket to create
        region (_type_, optional): String region to create bucket in, e.g 'ap-northeast-2'. Defaults to None.
    """

    # Create bucket
    try:
        if region is None:
            s3_client = boto3.client('s3')
            s3_client.create_bucket(Bucket=bucket_name)
    except ClientError as err:
        logging.error(err)
        return False
    return True

 

boto3.client('s3').create_bucket() 에는 두가지 argument가 가장 많이 활용된다.

  1. Bucket: 생성하고자 하는 버킷의 이름
  2. CreateBucketConfiguration: 버킷을 생성하고자 하는 리전 정보

Bucket의 경우, string으로 생성하고자 하는 버킷의 이름을 그대로 전달하면 된다.

CreateBucketConfiguration의 경우, 딕셔너리로 wrapping한 리전의 정보가 들어가야 한다.

이게 무슨 말이냐면, 다음과 같이 location이라는 딕셔너리를 먼저 구성하고 LocationConstraint라는 키에 region 값을 넣어주게 된다.

location = {'LocationConstraint': region}
s3_client.create_bucket(Bucket=name, CreateBucketConfiguration=location)

 

이때, argument 값은 항상 keyword argument로 제공되어야 한다.

location = {'LocationConstraint': region}
s3_client.create_bucket(Bucket=name, location)

----------------------------------------------
OUTPUT:
s3_client.create_bucket(Bucket=name, location)                                                ^
SyntaxError: positional argument follows keyword argument