如何将逗号分隔列表参数转换为在CloudFormation中构建ARNs

5

我有一个输入参数,它是一组角色名称:

Parameters:
  UserRoles:
    Type: CommaDelimitedList
    Default: ""
现在我想在策略文件主体中使用这些角色。如果只有一个角色,我会这样做:
        Principal:
          AWS:
            - !Join
              - ''
              - - 'arn:aws:iam::'
                - !Ref 'AWS::AccountId'
                - ':role/'
                - !Ref UserRole

但现在我希望对于不确定数量的角色进行操作。因此,我需要一些"Fn::Map"函数来处理字符串列表,以将角色名称转换为Arns。

这种操作可行吗?


我有类似的需求,但是需要将一个数组映射到一组资源。你最后解决了这个问题吗? - Larry Anderson
这个回答解决了你的问题吗?使用Cloudformation Join函数和CommaDelimitedList参数构建IAM ARNs - Error - Syntactical Remorse
2个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
2

使用 CloudFormation 原生结构没有立即的解决方案,但您可以通过使用宏来构建一个解决方案。

下面是一个完整的示例。总之,该解决方案有两个组件:

  1. 创建用于所需字符串操作的宏的 CloudFormation 堆栈
  2. 部署资源的 CloudFormation 堆栈。此堆栈使用第一个堆栈部署的宏

以下示例解答了这里提出的直接问题,但对于想要进行自定义字符串操作的一般读者也应该有用。


构建自定义字符串操作宏

以下模板创建由 Lambda 函数支持的宏。调用宏时会执行 Lambda 函数。

宏(因此是 Lambda)将逗号分隔的角色列表(例如 role1,role2)和 AWS 帐户 ID 作为输入,并返回格式化的 IAM 角色(例如 [arn:aws:iam::12345678910:role/role1,arn:aws:iam::12345678910:role/role2])。

这是完整的模板:

AWSTemplateFormatVersion: 2010-09-09
Resources:
  TransformExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service: [lambda.amazonaws.com]
            Action: ['sts:AssumeRole']
      Path: /
      Policies:
        - PolicyName: root
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action: ['logs:*']
                Resource: 'arn:aws:logs:*:*:*'
  TransformFunction:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        ZipFile: |
          import traceback
          def handler(event, context):
              response = {
                  "requestId": event["requestId"],
                  "status": "success"
              }
              try:
                  role_names = event["params"]["RoleNames"]
                  account_id = str(event["params"]["AccountId"])

                  role_formatter = lambda role : "arn:aws:iam::" + account_id + ":role/" + role
                  formatted_roles = list(map(role_formatter,role_names))

                  response["fragment"] = formatted_roles

              except Exception as e:
                  traceback.print_exc()
                  response["status"] = "failure"
                  response["errorMessage"] = str(e)
              return response
      Handler: index.handler
      Runtime: python3.6
      Role: !GetAtt TransformExecutionRole.Arn
  TransformFunctionPermissions:
    Type: AWS::Lambda::Permission
    Properties:
      Action: 'lambda:InvokeFunction'
      FunctionName: !GetAtt TransformFunction.Arn
      Principal: 'cloudformation.amazonaws.com'
  Transform:
    Type: AWS::CloudFormation::Macro
    Properties:
      Name: 'FormatIamRoles'
      Description: Provides various string processing functions
      FunctionName: !GetAtt TransformFunction.Arn

使用自定义宏进行字符串操作

下面的模板展示了如何使用先前部署的自定义宏来创建一个S3存储桶的策略。

该模板需要输入S3存储桶的名称和逗号分隔的IAM角色名称列表。

自定义宏(参见'Fn::Transform'的用法)需要输入逗号分隔的IAM角色名称列表和AWS账户ID。它返回格式化后的IAM角色列表,并将其用于为指定的S3存储桶创建策略。

Parameters:
  UserRoles:
    Type: CommaDelimitedList
    Default: "role1,role2"
  MyBucket:
    Type: String
    Default: my-bucket
Resources:
  MyBucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      Bucket: !Ref MyBucket
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Sid: MyRoleAllow
            Effect: Allow
            Principal: 
              AWS: 
                'Fn::Transform':
                  - Name: 'FormatIamRoles'
                    Parameters:
                      RoleNames: !Ref UserRoles
                      AccountId: !Ref 'AWS::AccountId'
            Action:
              - s3:*
            Resource: !Sub arn:aws:s3:::${MyBucket}/*
完成堆栈部署后,您会发现IAM角色已添加到存储桶中:

enter image description here


1
是的,这在纯CloudFormation中是可能的,但很困难且需要一些技巧。您需要滥用几乎所有可用的CloudFormation函数。 请考虑以下步骤: 1. 首先添加一个参数并要求逗号分隔的输入。 2. 使用逗号填充参数以强制为空值,并使用!Select和!Not来确定有多少个不为空。 3. 然后为每个设置的值设置一个条件(即列表中有一个项目?两个?三个?)。 4. 然后对于每个条件为true的情况,可以使用!Select在参数列表中查找该值。 这里有一个例子。请原谅我没有将所有内容拆分成纯YAML,我保留了JSON以使其至少有些可读性,但像PyCharm这样的工具会发出警告,尽管AWS认为它很好:
AWSTemplateFormatVersion: "2010-09-09"
Parameters:
  MyCommaSeparatedParameters:
    Type: String
    Default: FirstParam,SecondParam,ThirdParam

Conditions:
  # See the additional commas? That's to prevent erroring out when there's less than 3 items in the list
  ConditionParam0:    !Not [!Equals [!Select [0, !Split [',', !Sub '${MyCommaSeparatedParameters},,,']], '']]
  ConditionParam1:    !Not [!Equals [!Select [1, !Split [',', !Sub '${MyCommaSeparatedParameters},,,']], '']]
  ConditionParam2:    !Not [!Equals [!Select [2, !Split [',', !Sub '${MyCommaSeparatedParameters},,,']], '']]

Resources:
  Ec2InstanceIamDefaultPolicy:
    Type: "AWS::IAM::ManagedPolicy"
    Properties:
      ManagedPolicyName: "SomeRandomPolicy"
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
        - Effect: "Allow"
          Action:
          - "s3:GetObject"
          Resource:
          - !If
            - ConditionParam0
            - !Sub
                - "arn:aws:s3:::vopak-infra-automations/${param}"
                - param: !Select [0, !Split [',', !Sub '${MyCommaSeparatedParameters},,,']]
            - !Ref "AWS::NoValue"
          - !If
            - ConditionParam1
            - !Sub
                - "arn:aws:s3:::vopak-infra-automations/${param}"
                - param: !Select [1, !Split [',', !Sub '${MyCommaSeparatedParameters},,,']]
            - !Ref "AWS::NoValue"
          - !If
            - ConditionParam2
            - !Sub
                - "arn:aws:s3:::vopak-infra-automations/${param}"
                - param: !Select [2, !Split [',', !Sub '${MyCommaSeparatedParameters},,,']]
            - !Ref "AWS::NoValue"
你可能需要使用一个 Condition 属性,以一组单独的角色来创建你想要的内容,而不是基于列表的创建方式,就像我在这里所做的那样。

这意味着为逗号分隔列表中的每个值创建一个条件,对吗?这不够灵活。 - Paolo
不,它根本不灵活。这不是一个好的解决方案,唯一可取的论点是它完全基于CloudFormation,而不需要Lambda宏。 - b0tting

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,