본문 바로가기

Storage&CDN/S3

Amazon S3 임시 자격 증명(assume_role), Bucket Prefix 별 오브젝트 사이즈 체크

import boto3
from boto3.session import Session

def assume_role():
    client = boto3.client('sts')
    account_id = client.get_caller_identity()["Account"]

    IAM_ROLE_ARN = 'arn:aws:iam::58xxx119:role/xxRole'
    IAM_ROLE_SESSION_NAME = 'xxRole'
    REGION_NAME = 'ap-northeast-1'

    response = client.assume_role(
                RoleArn=IAM_ROLE_ARN,
                RoleSessionName=IAM_ROLE_SESSION_NAME
                )

    session = Session(aws_access_key_id=response['Credentials']['AccessKeyId'], aws_secret_access_key=response['Credentials']['SecretAccessKey'], aws_session_token=response['Credentials']['SessionToken'], region_name=REGION_NAME)
    #client = session.client('sts')
    #account_id = client.get_caller_identity()["Account"]

    return response['Credentials']['AccessKeyId'], response['Credentials']['SecretAccessKey'], response['Credentials']['SessionToken']

def get_folder_size(bucket, prefix, accessKey, secretKey, token):
    total_size = 0
    AWS_ACCESS_KEY_ID = accessKey
    AWS_SECRET_ACCESS_KEY = secretKey
    AWS_DEFAULT_REGION = "ap-northeast-2"
    s3_client = boto3.resource("s3", region_name='ap-northeast-1', aws_access_key_id=accessKey, aws_secret_access_key=secretKey, aws_session_token=token)
    for obj in s3_client.Bucket(bucket).objects.filter(Prefix=prefix):
        total_size += obj.size
    return total_size/1024/1024/1024

if __name__ == "__main__":
    session = assume_role()
    size = get_folder_size("bucketName", "prefix", session[0], session[1], session[2])
    print(size)