Cloudformation如何从另一个堆栈引用Managed-Policy

时间:2016-03-09 15:11:57

标签: amazon-iam amazon-cloudformation

我有以下角色。从内部我想使用另一个堆栈中的现有托管策略。

我该怎么办?

"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 个答案:

答案 0 :(得分:1)

现在使用Imports/Exports支持这种方式。基本上,创建策略的堆栈具有包含策略名称(或ARN,不确定在这种情况下需要哪个)的输出,并将其声明为具有区域唯一名称的导出。然后,其他堆栈可以使用Import函数来使用它。

例如,如果以下堆栈(让我们说它名为FooStack)创建托管策略,则其输出中可以包含以下内容:

"Outputs" : {
    "MyManagedPolicy" : {
        "Value" : { "Ref" : "MyManagedPolicy" },
        "Export" : { "Name" : {"Fn::Sub": "${AWS::StackName}-MyManagedPolicy" }}
    }
}

另一个堆栈可以使用它:

"Policies": [
    { "Fn::ImportValue" : "FooStack-MyManagedPolicy" }
]

答案 1 :(得分:0)

如果您的要求是独立的可共享策略。那么您需要将其设置为ManagedPolicy,而不是标准的Policy

一个例子:

1

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

2

导出:

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

然后在您要在其中一个角色中导入此独立托管策略的其他堆栈中,执行以下操作:

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:
              - .....

答案 2 :(得分:-1)

根据 Ref CF函数的docs,您应该可以使用它来通过其逻辑名称检索托管策略资源。

例如:

Policies: [
  { "Ref" : "MyManagedPolicy" }
]

其中“ MyManagedPolicy ”将是您在CF模板中定义的资源的名称:

"MyManagedPolicy" : {
  "Type": "AWS::IAM::ManagedPolicy",
  "Properties": {
    "Description" : String,
    "Groups" : [ String, ... ],
    "Path" : String,
    "PolicyDocument" : JSON object,
    "Roles" : [ String, ... ],
    "Users" : [ String, ... ]
  }
}

希望这有帮助吗?