Follow these steps in order to create a cross-account role:
- Start a new template with a version and description:
AWSTemplateFormatVersion: "2010-09-09"
Description: This template creates a role that can be assumed from another account.
- The template will take one parameter—the source account that can assume the role:
Parameters:
SourceAccountNumber:
Type: String
Description: The AWS account number to grant access to assume
the role.
AllowedPattern: "[0-9]+"
MaxLength: "12"
MinLength: "12"
- The role itself will consist of the trust role and a sample policy:
Resources:
CrossAccountRole:
Type: "AWS::IAM::Role"
Properties:
Path: "/"
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: ""
Action: "sts:AssumeRole"
Effect: Allow
Principal:
AWS: !Sub "arn:aws:iam::${SourceAccountNumber}:root"
Policies:
- PolicyName: DoEverything
PolicyDocument:
Version: "2012-10-17"
Statement:
- Action:
- "*"
Effect: Allow
Resource: "*"
Sid: DoEverything
This role has full access to the target account.
- Finally, we create an output that will make it easy to retrieve the target role ARN:
Outputs:
RoleARN:
Description: The Role ARN that can be assumed by the
other account.
Value: !GetAtt CrossAccountRole.Arn
- Save the template with a known name, for example, 08-03-CrossAccountRoles.yaml.
- Deploy the role to the target account (that is, account B), by using the CLI tool:
aws cloudformation create-stack
--stack-name CrossAccountRole
--template-body file://src/08-03-CrossAccountRoles.yaml
--parameters
ParameterKey=SourceAccountNumber,
ParameterValue=<your-source-account-number>
--capabilities CAPABILITY_IAM
- Get (just) the target role ARN from the outputs of your CloudFormation stack:
aws cloudformation describe-stacks
--stack-name CrossAccountRole
--query 'Stacks[0].Outputs[0].OutputValue'
--output text
- In your source account (that is, account A) confirm that you can assume the target role, by manually invoking the CLI tool:
aws sts assume-role
--role-arn <your-target-role-arn>
--role-session-name CrossAccountRole