본문 바로가기

AWS

[AWS] boto3로 sts 임시 자격 증명 얻기

boto3로 자격증명을 얻어 리소스 조회하는 방법

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sts.html

 

STS - Boto3 1.34.158 documentation

Previous ListVolumes

boto3.amazonaws.com

 

임시 자격 증명 발급

boto3를 사용하기 위해 IAM User와 Access key가 필요하다.

import boto3
from pytz import timezone
from pprint import pprint

# 함수 선언
def assume_role(role_arn, role_session_name, duration_seconds=1000):
    sts_client = boto3.client("sts", region_name="ap-northeast-2")

    response = sts_client.assume_role(
        RoleArn=role_arn,
        RoleSessionName=role_session_name,
        DurationSeconds=duration_seconds,
    )

    credentials = response["Credentials"]

    print(f"sts assume successfully.")

    return {
        "AccessKeyId": credentials["AccessKeyId"],
        "SecretAccessKey": credentials["SecretAccessKey"],
        "SessionToken": credentials["SessionToken"],
        "Expiration": credentials["Expiration"]
        .astimezone(timezone("Asia/Seoul"))
        .strftime("%Y.%m.%d, %H:%M:%S"),
    }

# 함수를 호출할 변수
role_arn = "arn:aws:iam::123412341234:role/s3-default-role"
role_session_name = "tempSession"
duration_seconds = 1000

sts_temp = assume_role(role_arn, role_session_name, duration_seconds)
pprint(sts_temp)

 

해당 코드를 실행하면 아래와 같이 임시 자격증명을 얻을 수 있다.

 

 

 

임시 자격 증명 등록

위에서 얻은 key 값들을 user profile에 등록해주면 된다.

def configure_aws_profile(profile_name, access_key_id, secret_access_key, session_token):
    key_type = ["aws_access_key_id", "aws_secret_access_key", "aws_session_token"]
    temp_key_list = [access_key_id, secret_access_key, session_token]

    [subprocess.run(["aws","configure","set","--profile",profile_name,key_type[i],temp_key_list[i]]) for i in range(3)]

    print(f"AWS profile '{profile_name}' configured successfully.")


# 변수 선언
profile_name = "s3"
access_key_id = sts_temp["AccessKeyId"]
secret_access_key = sts_temp["SecretAccessKey"]
session_token = sts_temp["SessionToken"]
region = "ap-northeast-2"

# 함수 실행
configure_aws_profile(profile_name, access_key_id, secret_access_key, session_token)

 

이후 CLI로 사용하거나 boto3를 통해 s3에 접근하면 된다.

aws s3 ls --profile s3
import boto3

# 함수 선언
def list_s3_buckets(access_key_id, secret_access_key, session_token, region):

    # boto3 클라이언트 생성
    s3_client = boto3.client('s3',
                        aws_access_key_id=access_key_id,
                        aws_secret_access_key=secret_access_key,
                        aws_session_token=session_token,
                        region_name=region
                        )
    # 버킷 목록을 저장할 리스트 생성
    bucket_list = []

    # 버킷 목록 가져오기
    try:
        response = s3_client.list_buckets()
        # 가져온 버킷 목록 처리
        if 'Buckets' in response:
            for bucket in response['Buckets']:
                bucket_list.append(bucket['Name'])
        else:
            print("No buckets found")
    except Exception as e:
        print(f"An error occurred: {e}")

    return bucket_list

# 변수 선언
access_key_id = tempCred["AccessKeyId"]
secret_access_key = tempCred["SecretAccessKey"]
session_token = tempCred["SessionToken"]
region = "ap-northeast-2"

# 함수 실행
list_s3_buckets(access_key_id, secret_access_key, session_token, region)

 

'AWS' 카테고리의 다른 글

[AWS] boto3로 DynamoDB에 데이터 넣기  (0) 2024.08.19
[AWS] Boto3로 s3에 있는 파일 읽기  (0) 2024.08.13
[AWS] aws sts & assume role - (2)  (0) 2024.08.12
[AWS] aws sts & assume role - (1)  (0) 2024.07.26
[AWS] AWS API 동작 방식  (1) 2024.07.21