How can I attach an IAM managed policy to an IAM role in AWS CloudFormation?
Last updated: 2019-05-30
How can I add an existing or new AWS Identity and Access Management (IAM) managed policy to an IAM role in AWS CloudFormation?
Short Description
To add an existing or new IAM managed policy to an IAM role resource, use the ManagedPolicyArns property of resource type AWS::IAM::Role. Your IAM managed policy can be an AWS managed policy or a customer managed policy.
Important: You can attach a maximum of 10 managed policies to an IAM role or user. The size of each managed policy can't exceed 6,144 characters. For more information on size limitations, see Limitations on IAM Entities and Objects.
Resolution
Add an existing IAM managed policy to an IAM role
To pass an existing managed policy or policy as a parameter or parameters to an AWS CloudFormation stack, complete the following steps:
1. In your AWS CloudFormation template, create a parameter or parameters that you can use to pass in the ARN of your IAM managed policy. See the following example:
Parameters:
awsExampleManagedPolicyParameterOne:
Type: String
Description: awsExampleIAMManagedPolicyARNOne
awsExampleManagedPolicyParameterTwo:
Type: String
Description: awsExampleIAMManagedPolicyARNTwo
2. In the Resources section of your template, for the resource of type AWS::IAM::Role, set Ref to the parameter or parameters that you created in step 1 (awsExampleManagedPolicyParameterOne, awsExampleManagedPolicyParameterTwo). See the following example:
Resources:
RootRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: /
ManagedPolicyArns:
- !Ref awsExampleManagedPolicyParameterOne
- !Ref awsExampleManagedPolicyParameterTwo
Add a new IAM managed policy to an IAM role
1. In your AWS CloudFormation template, create a new policy using the AWS::IAM::ManagedPolicy resource. See the following example:
SampleManagedPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
PolicyDocument:
Version: "2012-10-17"
Statement:
-
Sid: AllowAllUsersToListAccounts
Effect: Allow
Action:
- iam:ListAccountAliases
- iam:ListUsers
- iam:GetAccountSummary
Resource: "*"
2. Use the !Ref logical ID syntax to attach the IAM managed policy resource to the AWS::IAM::Role resource. Set Ref to the resource logical ID that you created previously (SampleManagedPolicy). See the following example:
RootRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: /
ManagedPolicyArns:
- !Ref SampleManagedPolicy
Did this article help you?
Anything we could improve?
Need more help?