Using the AssumeRole functionality in AWS, you can grant temporary access to resources in one AWS account (account_1) to another AWS account (account_2). In our scenario, we want to access an S3 bucket named “normalised_s3_data” in account_1 using an IAM role named “ALLOWED_ROLE_NAME” in account_2.
Create a Role in account_1
In the AWS Management Console of account_1, navigate to the IAM (Identity and Access Management) service. Create a new role with the necessary permissions to access the S3 bucket “normaliser”. Assign permissions policies like AmazonS3ReadOnlyAccess
or custom policies granting the required S3 access.
Trust Relationship
While creating the role in account_1, define a trust relationship that allows account_2 to assume this role. The trust relationship JSON should contain the AWS account ID of account_2 and the service or application (uip_dnr_ml_transfer
) that will assume this role.
Example trust relationship JSON:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::ACCOUNT_2_ID:ALLOWED_ROLE_NAME"
},
"Action": "sts:AssumeRole",
"Condition": {}
}
]
}
Assume Role from account_2
In the application “uip_dnr_ml_transfer” running in account_2, you will need to use AWS SDK or AWS CLI to assume the role created in account_1. You will need the ARN (Amazon Resource Name) of the role created in account_1.
Example code in Python using AWS SDK (Boto3):
import boto3
# Assume the role in account_1
sts_client = boto3.client('sts')
assumed_role = sts_client.assume_role(
RoleArn='arn:aws:iam::ACCOUNT_1_ID:role/ROLE_NAME',
RoleSessionName='AssumedRoleSession'
)
# Use the temporary credentials to access the S3 bucket
s3_client = boto3.client(
's3',
aws_access_key_id=assumed_role['Credentials']['AccessKeyId'],
aws_secret_access_key=assumed_role['Credentials']['SecretAccessKey'],
aws_session_token=assumed_role['Credentials']['SessionToken']
)
# Now you can interact with the S3 bucket
response = s3_client.list_objects(Bucket='normaliser')
print(response)
Remember to replace ACCOUNT_1_ID, ACCOUNT_2_ID, and ROLE_NAME with the appropriate values from your setup.
This process allows the IAM role “ALLOWED_ROLE_NAME” in account_2 to temporarily assume the role created in account_1, granting it the necessary permissions to access the “normalised_s3_data” S3 bucket.