def assume_sts_role()

in Back-End/lambdas/receive_sqs_message.py [0:0]


def assume_sts_role(account_to_assume, cross_account_role_name):

    # https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-api.html
    sts_client = boto3.client('sts')
    cross_account_role_arn = f'arn:aws:iam::{account_to_assume}:role/{cross_account_role_name}'

    try:

        # Call the assume_role method of the STSConnection object and pass the role
        # ARN and a role session name.
        credentials = sts_client.assume_role(
            RoleArn=cross_account_role_arn,
            RoleSessionName='TemporaryRole'

        )['Credentials']

        # Make temp creds
        temporary_credentials = boto3.Session(
            aws_access_key_id=credentials['AccessKeyId'],
            aws_secret_access_key=credentials['SecretAccessKey'],
            aws_session_token=credentials['SessionToken'],
        )

        # return creds
        return temporary_credentials

    except ClientError as e:
        print(
            f'Error: on Account: {account_to_assume} with Role: {cross_account_role_arn}')
        print(f'{cross_account_role_name} might not exists in account?')
        raise e