A snippet to quickly configure a lambda for cross-account and cross-region
Let us consider we have 2 lambda functions named Invoker and Invokee
- Invoker function in eu-west-2 in 123456789101 account
- Invokee function in us-west-1 in 110987654321 account
- Invoker function
import json
import boto3
def lambda_handler(event, context):
# mention cross region here
client = boto3.client('lambda', region_name='us-west-1') # function you need to invoke from cross account/region
response = client.invoke(FunctionName='arn:aws:lambda:us-west-1:110987654321:function:invokee', InvocationType='RequestResponse')
responsefinal = json.load(response['Payload'])
print(responsefinal)return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda from invoker function!')
}
- Invokee function
import json
import boto3def lambda_handler(event, context):
# TODO implement
boto3.client('lambda',region_name='us-west-1')
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda from invokee!')
}
1. Invoker functions execution role should allow the function to assume IAM role in another account
Thus, add the following into the execution role of Invoker by adding inline policy:
{
"Version": "2012–10–17",
"Statement": {
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": "arn:aws:iam::110987654321:role/service-role/invokee-role"
}
}
2. Modify Invokee trust policy to allow Invoker function to assume the role
Add following in trust policy of invoke function, by keeping the existing policy as it is.
{
"Version": "2012–10–17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::123456789101:role/service-role/invoker-function-eu-west2-role"
},
"Action": "sts:AssumeRole"
}
]
}
The final policy should look like this:
{
"Version": "2012–10–17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
},
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::123456789101:role/service-role/invoker-function-eu-west2-role"
},
"Action": "sts:AssumeRole"
}
]
}
3. Add resource-based policy in Invokee function by mentioning Invoker role as arn/principal and Lambda:invoke function as action.
- Go to the Permissions tab of the Invokee function and go to Resource policy and add the following:
Statement ID: any unique ID
Principal: arn:aws:iam::123456789101:role/service-role/invoker-function-eu-west2-role
Action: lambda:InvokeFunction
4. Add the following policy to the execution role of the Invoker function to allow it to invoke lambda.
{
"Version": "2012–10–17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "lambda:InvokeFunction",
"Resource": "arn:aws:lambda:*:*:*"
}
]
}
After following all the steps you should be able to execute the Invoker function which should invoke the Invokee function in cross account/region.