AWS Cross Account Access
In this exercise, I will try few ways to access resources in Account A for a user in Account B.
Setup
- Have two accounts ready, Account A and Account B
- Go to Account A console
- Create a Role with “Another AWS account” as the type of trusted entity, role name as crossaccountrole
- Attach policies, for example AmazonS3FullAccess
Access Account A resouce from Account B
Access from console
- Go to Account B console
- Click switch role
- Provide account id of Account A and the role name of crossaccountrole created earlier
- Now we should be able to access S3 in Account B
- Or use https://signin.aws.amazon.com/switchrole?account=account_id_number&roleName=role_name&displayName=text_to_display
Access from command line
- Access from AWS Cli with config profile
# Add a profile in ~/.aws/config
[profile crossaccountaccess]
role_arn = arn:aws:iam::${account_a_id}:role/crossaccountrole
source_profile = default
# Test the access
aws s3 ls --profile crossaccountaccess
- Or access from AWS Cli with assume role
# install jq, use this to parse JSON response
yum install epel-release -y
yum update -y
yum install jq -y
# check current caller identity
aws sts get-caller-identity --query 'Account' --output text
# Assume the role to get a temp credentials which can be used to access the resource in Account A
ASSUMED_ROLE=$(aws sts assume-role --role-arn arn:aws:iam::${account_a_id}:role/crossaccountrole --role-session-name AWSCLI-Session)
export AWS_ACCESS_KEY_ID=$(echo "${ASSUMED_ROLE}" | jq -r .Credentials.AccessKeyId)
export AWS_SECRET_ACCESS_KEY=$(echo "${ASSUMED_ROLE}" | jq -r .Credentials.SecretAccessKey)
export AWS_SESSION_TOKEN=$(echo "${ASSUMED_ROLE}" | jq -r .Credentials.SessionToken)
export AWS_DEFAULT_REGION=us-east-1
# check current caller identity
aws sts get-caller-identity
# Test the access
aws s3 mb s3://testbucketfromaccountb123
aws s3 ls
# return to IAM user with removing the environment vaiables
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_DEFAULT_REGION
# check current caller identity
aws sts get-caller-identity