728x90

AWS에서 boto3는 AWS 서비스와 상호작용할 수 있는 Python SDK입니다. AssumeRole을 사용하여 임시 자격 증명을 얻는 것은 Multi Account 관리 구조에서 특정 권한이 부여된 역할로 작업할 때 유용합니다.

STS란 무엇인가
STS(Security Token Service)는 AWS 서비스에서 임시 자격 증명을 얻기 위한 서비스로 AssumeRole API를 호출하여 제한된 기간 동안 사용할 수 있는 액세스 키, 비밀 키, 세션 토큰을 얻을 수 있습니다. 이 임시 자격 증명은 다른 계정에서의 리소스에 접근하거나, 기존 사용자 권한을 대체하는 데 사용됩니다.

1. 사전 요구사항

  • Python 환경: Python 3.7+
  • Boto3 설치: boto3 라이브러리는 AWS SDK이므로 설치( pip install boto3)
  • AWS IAM 역할: AssumeRole을 사용할 수 있는 권한을 가진 IAM 역할과 정책이 설정

2. AWS IAM 역할 설정

2.1 Assume Role 및 정책 설정

Principal에 접근을 허용하고자 하는 사용자를 추가

{Account}{UserName} 영역에 Role을 위임(Assume) 받을 ARN 정보를 입력 합니다.
그리고, 필요한 정책을 부여합니다. 예) S3FullAcess

2. boto3에서 임시 자격 증명 얻기

Boto3에서 임시 자격 증명을 얻으려면 sts 클라이언트를 생성하고, assume_role 메서드를 사용하여 임시 자격 증명을 요청할 수 있습니다.

import boto3
from botocore.exceptions import ClientError

def assume_role(role_arn, session_name):
    sts_client = boto3.client('sts')

    try:
        # Assume Role 호출
        assumed_role_object = sts_client.assume_role(
            RoleArn=role_arn,
            RoleSessionName=session_name
        )

        # 임시 자격 증명 가져오기
        credentials = assumed_role_object['Credentials']

        # 액세스 키, 비밀 키, 세션 토큰 반환
        return {
            'access_key': credentials['AccessKeyId'],
            'secret_key': credentials['SecretAccessKey'],
            'session_token': credentials['SessionToken']
        }

    except ClientError as e:
        print(f"AssumeRole 실패: {e}")
        return None

3.1 파라미터 설명

RoleArn: Assume할 역할의 Amazon Resource Name (ARN)을 나타냅니다. 예) arn:aws:iam::123456789012:role/example-role
RoleSessionName: 세션에 사용할 이름입니다. 이 이름은 각 요청에 대해 고유해야 합니다.

3.2 실행 예시

AssumeRole을 호출하고, 그 자격 증명을 사용하여 S3 버킷 리스트를 가져오는 예제(파이썬) 입니다.

# S3 클라이언트를 생성하는 코드
def create_s3_client_with_assumed_role(credentials):
    s3_client = boto3.client(
        's3',
        aws_access_key_id=credentials['access_key'],
        aws_secret_access_key=credentials['secret_key'],
        aws_session_token=credentials['session_token']
    )
    return s3_client

if __name__ == "__main__":
    role_arn = "arn:aws:iam::123456789012:role/example-role"
    session_name = "example-session"

    # 임시 자격 증명 얻기
    credentials = assume_role(role_arn, session_name)

    if credentials:
        # 임시 자격 증명으로 S3 클라이언트 생성
        s3_client = create_s3_client_with_assumed_role(credentials)

        # S3 버킷 리스트 가져오기
        response = s3_client.list_buckets()
        print("S3 Buckets:", [bucket['Name'] for bucket in response['Buckets']])

결론

Assume Role을 사용하면 임시 자격 증명을 얻고, 이를 활용하여 안전하게 여러 계정에서 작업하거나 제한된 권한으로 특정 작업을 수행할 수 있습니다.

728x90
반응형

+ Recent posts