Cloudformation how to reference Managed-Policy from another stack

Viewed 8601

I have the following role. From within it I want to use an existing managed policy from another stack.

How can I do so?

"TestRole": {
    "Properties": {
      "AssumeRolePolicyDocument": {
        "Statement": [
          {
            "Action": [
              "sts:AssumeRole"
            ],
            "Effect": "Allow",
            "Principal": {
              "Service": [
                "lambda.amazonaws.com"
              ]
            }
          }
        ],
        "Version": "2012-10-17"
      },
      "Path": "/lambda/",
      "Policies": [
        ??????
      ]
    },
    "Type": "AWS::IAM::Role"
  }
3 Answers

If your requirement is a stand-alone sharable policy. then you need to make it as ManagedPolicy and not a standard Policy.

An Example:

1

MyManagedPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
  Path: "/"
  PolicyDocument:
    Version: "2012-10-17"
    Statement:
      - Effect: "Allow"
        Action:
          - "s3:*"
        Resource:
          - Fn::GetAtt: MyBucket.Arn

2

Export it:

MyManagedPolicy:
Description: MyManagedPolicy
Value:
  Ref: MyManagedPolicy
Export:
  Name:
    Fn::Join:
      - "-"
      - - "MyManagedPolicy"
        - Ref: StackName

Then in your other stack where you want to import this stand-alone managed policy in one of your roles, do this:

MyUserRole:
Type: "AWS::IAM::Role"
Properties:
  RoleName: "SomeName"
  AssumeRolePolicyDocument:
    Version: "2012-10-17"
    Statement:
      - Effect: "Allow"
        Principal:
          AWS: 
            - .....
        Action:
          - .....  
  Path: "/"
  ManagedPolicyArns:
    - Fn::ImportValue:
        Fn::Sub: "MyManagedPolicy-${StackName}"
  Policies:
    - PolicyName: "NameOfYouInlinePolicyWithoutSpaces"
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: "Allow"
            Action:
              - .....
            Resource:
              - .....
Related