In a multi-account AWS setup, enabling cross-account access allows services like Lambda in one account to interact with resources in another account securely. Let’s walk through the process, illustrating each step with an example.
Step 1: Create a Cross-Account IAM Role
In the target account (Account B), create an IAM role (devops-role-cross-role) with permissions to access resources. Define a trust relationship to allow access from the account where the Lambda function resides (Account A).
Example Trust Relationship Policy:
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole",
"Condition": {
"StringEquals": {
"aws:SourceAccount": "ACCOUNT_A_ID"
}
}
}]
}Step 2: Attach Policies to the IAM Role
Attach policies granting necessary permissions for the Lambda function to interact with resources in Account B. For instance, policies to access EC2, S3, etc.
Step 3: Define the Lambda Function in Account A
Write the Lambda function code (in Account A) to assume the cross-account IAM role using sts:AssumeRole. Here's a simplified example:
import boto3
def lambda_handler(event, context):
sts_client = boto3.client('sts')
assumed_role = sts_client.assume_role(
RoleArn='arn:aws:iam::ACCOUNT_B_ID:role/devops-role-cross-role',
RoleSessionName='AssumedRoleSession'
)
# Use assumed role credentials to interact with resources in Account B
ec2_client = boto3.client(
'ec2',
aws_access_key_id=assumed_role['Credentials']['AccessKeyId'],
aws_secret_access_key=assumed_role['Credentials']['SecretAccessKey'],
aws_session_token=assumed_role['Credentials']['SessionToken']
)
# Perform operations on resources in Account B
# Example: Describe EC2 instances
response = ec2_client.describe_instances()
# Process response and return results
return responseStep 4: Attach IAM Policy to Lambda Function Role in Account A
Attach a policy to the Lambda function’s execution role in Account A, allowing it to assume the cross-account IAM role (devops-role-cross-role) in Account B.
Step 5: Testing and Deployment
Test the Lambda function to ensure it successfully accesses resources in Account B. Once tested, deploy the Lambda function for regular use.
Conclusion
This setup enables an AWS Lambda function in one account to securely access resources in another account through cross-account IAM roles. By following these steps and the provided example, you can establish secure cross-account communication, enhancing the flexibility and scalability of your AWS infrastructure.
Elevate your AWS infrastructure by implementing cross-account access for your Lambda functions today! Follow the detailed steps in this guide to securely connect resources across multiple accounts, streamlining your operations and maximizing the potential of your cloud services.







