AWS Lambda with cross account access using Assume Role in JAVA

Atul Sharma
2 min readNov 29, 2020

--

AWS Cross account access using JAVA

In this story we will see how we can execute cross account functionality using AWS Lambda via assuming role of different AWS Account.

End Goal

List all buckets present on AWS Account B from lambda present on AWS Account A, via assuming role present on Account B which as permissions to list S3 buckets.

This can be extended to any functionality once you have assumed the correct role from target account from parent account.

Configuring cross account access

  1. Create IAM role on Account A (parent account), which will be used to run our AWS lambda on parent account.
  2. Create IAM role on Account B (target account), and grant all permissions for the stuff you want to execute. For now, we need AmazonS3ReadOnlyAccess as we only need to list the buckets present on target AWS account (Account B).
  3. Now Go to Trust relationships of IAM role of target Account and edit relationships. We need to add RoleA to trust relationship of role B so, that role A can assume role B.

Edit the json file and update with the one provided. Edit, the arn-of-role-A with actual ARN of role A in parent AWS account.

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
},
{
"Effect": "Allow",
"Principal": {
"AWS": "arn-of-role-A"
},
"Action": "sts:AssumeRole"
}
]
}

Now our Role of Account A (parent account)is ready to Assume IAM role B of Account B (target account)

Creating Lambda with AWS STS

Now write a lambda to assume role B, once role B is assumed AWS STS will return temporary credentials of target account with permissions of role assumed which can be used with AWS SDK to perform desired operations.

Here’s some sample code in JAVA to assume the role.

This code, will list all S3 buckets on target account. You can use the credentialsProvider object to initialise any AWS SDK service and use it cross account.

--

--