3

This is about why AWS Lambda Service has been designed in this way.

According to the documentation on How can I configure a Lambda function to assume a role from another AWS account?, to access a resource from another account, the Lambda function needs to call the assume_role method to get temporary credentials. My question is why this cannot be done outside lambda. For example, we could just bind RoleB from AccountB to RoleA (the execute role of the lambda function).

The benefit of moving the logic outside is obvious - the lambda is more portable.

import boto3

def lambda_handler(context, event):

    sts_connection = boto3.client('sts')
    acct_b = sts_connection.assume_role(
        RoleArn="arn:aws:iam::222222222222:role/role-on-source-account",
        RoleSessionName="cross_acct_lambda"
    )

    ACCESS_KEY = acct_b['Credentials']['AccessKeyId']
    SECRET_KEY = acct_b['Credentials']['SecretAccessKey']
    SESSION_TOKEN = acct_b['Credentials']['SessionToken']

    # create service client using the assumed role credentials, e.g. S3
    client = boto3.client(
        's3',
        aws_access_key_id=ACCESS_KEY,
        aws_secret_access_key=SECRET_KEY,
        aws_session_token=SESSION_TOKEN,
    )

    return "Hello from Lambda"

Once the logic was moved out, the above code can be simplified as:

import boto3

def lambda_handler(context, event):

   # create service client e.g. S3
    client = boto3.client(
        's3'
    )

    return "Hello from Lambda"

0 Answers0