2
votes

Using AWS, I'm building a cloud formation stack defining:

  1. A Managed Policy called MyPolicy
  2. A Role called MyRole that should attach that policy

The stack will be created by an admin ; and once created, the goal is to allow (from outside the stack) some users to assume MyRole.

My question: How should the role be defined in order to attach that policy ?


The AWS help page of the role properties suggests to use the ManagedPolicyArns, but I get various errors depending on how I refer to MyPolicy:

If I use the GetAtt function to retrieve the policy's arn, I get an error at the template validation:

"ManagedPolicyArns": [ { "Fn::GetAtt" : [ "MyPolicy", "Arn" ] } ]

Template error: resource MyPolicy does not support attribute type Arn in Fn::GetAtt


And If I use the Join function to build the policy's arn, I get an error during the role creation.

"ManagedPolicyArns": [ { "Fn::Join" : [ "", [ "arn:aws:iam::", { "Ref": "AWS::AccountId" }, ":policy/", { "Ref": "MyPolicy" } ] ] } ]

ARN arn:aws:iam::aws:policy/arn:aws:iam::«my-account-id»:policy/MyPolicy is not valid. (Service: AmazonIdentityManagement; Status Code: 400; Error Code: InvalidInput; Request ID: «an-id»)


Below is my stack definition using JSON format:

{
    "AWSTemplateFormatVersion" : "2010-09-09",
    "Resources" : {
        "MyPolicy" : {
            "Type": "AWS::IAM::ManagedPolicy",
            "Properties": {
                "ManagedPolicyName" : "MyPolicy",
                "PolicyDocument" : {
                    "Version": "2012-10-17",
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Action": [ "s3:*" ],
                            "Resource": "arn:aws:s3:::the-bucket"
                        }
                    ]
                }
            }
        },

        "MyRole" : {
            "Type": "AWS::IAM::Role",
            "RoleName": "MyRole",
            "AssumeRolePolicyDocument": {
                "Version": "2012-10-17",
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Principal": { "AWS": {"Fn::Join" : [ "", [ "arn:aws:iam::", { "Ref": "AWS::AccountId" }, ":root" ] ] } },,
                        "Action": [ "sts:AssumeRole" ]
                    }
                ]
            },
            "ManagedPolicyArns": [
                { "Fn::GetAtt" : [ "MyPolicy", "Arn" ] }
            ]
        }
    }
}
1

1 Answers

1
votes

{"Ref": "MyPolicy"} will return the ARN of the managed policy created by your stack. Your error message indicates that. Also, check this AWS documentation.