code-dumps/py/aws-assume-role-chained.py
2023-04-21 13:01:56 +08:00

27 lines
1002 B
Python

import json
import boto3
import base64
def lambda_handler(event, context):
# layer1
l1client = boto3.client('sts')
assumed_role_object=l1client.assume_role(
RoleArn="arn:aws:iam::111122223333:role/Role1",
RoleSessionName="lambda-assumeRoleL1"
)
# layer2
l2client = boto3.client(
'sts',
aws_access_key_id=assumed_role_object['Credentials']['AccessKeyId'],
aws_secret_access_key=assumed_role_object['Credentials']['SecretAccessKey'],
aws_session_token="lambda-assumeRoleMs")
l2_assumed_role_object=l2client.assume_role(
RoleArn="arn:aws:iam::111122223333:role/Role2",
RoleSessionName="lambda-assumeRoleL2"
)
print("export AWS_ACCESS_KEY_ID=" + l2_assumed_role_object['Credentials']['AccessKeyId'])
print("export AWS_SECRET_ACCESS_KEY=" + l2_assumed_role_object['Credentials']['SecretAccessKey'])
print("export AWS_SESSION_TOKEN=" + l2_assumed_role_object['Credentials']['SessionToken'])
print("export AWS_DEFAULT_REGION=ap-east-1")