Cloudformation can I create a new role referencing an existing policy

amazon-cloudformationamazon-iam

At the moment I have a shared S3 bucket which has specific access to particular key paths (i.e. folders) for different instances. I've been able to create instance profile with my new role and test no problem limiting to access to that folder.

My problem is that there is an existing generic role with defined policies, that I also want to be able to include in my new role for each stack.

In cloudformation is it possible to include policies defined in one role to be included in another role without having to redefine the policy document in the new role?

Something like the following:

"AppTierS3AccessRole": {
        "Type": "AWS::IAM::Role",
        "Properties": {
            "AssumeRolePolicyDocument": {
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Principal": {
                            "Service": [ "ec2.amazonaws.com" ]
                        },
                        "Action": [ "sts:AssumeRole" ]
                    }
                ]
            },
            "Path": "/",
            "Policies": [ { "Ref": "existing-policy" } ]
        }
    },

The "existing-policy" being the important part here. I have tried to find the arn of the existing policy to try and reference it but I'm a bit stuck.

Best Answer

src: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html

The AWS::IAM::Role types now have a ManagedPolicyArns field where you can set this. You just need to grab the ARN (easy to grab from IAM console) and place it in that field. In the example below I created a role that provides read-only ECR access so my image can pull docker containers from ECR.

  ecrRole:
    Type: AWS::IAM::Role
    Properties:
      Path: "/"
      ManagedPolicyArns:
        - "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly"
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - ec2.amazonaws.com
          Action:
          - sts:AssumeRole