如何转换 CommaDelimitedList 参数以在 CloudFormation 中构建 ARN

Nat*_*han 5 amazon-web-services aws-cloudformation

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

Parameters:
  UserRoles:
    Type: CommaDelimitedList
    Default: ""
Run Code Online (Sandbox Code Playgroud)

现在我想在策略文档主体中使用这些角色。如果只有 1 个角色,我会这样做:

        Principal:
          AWS:
            - !Join
              - ''
              - - 'arn:aws:iam::'
                - !Ref 'AWS::AccountId'
                - ':role/'
                - !Ref UserRole
Run Code Online (Sandbox Code Playgroud)

但现在我想为不同数量的角色做到这一点。因此,我需要在字符串列表上使用某种“Fn::Map”函数,允许我将角色名称转换为 Arns。

那可能吗?

Unb*_*ess 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
Run Code Online (Sandbox Code Playgroud)

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

The following template illustrates how the custom macro previously deployed can be used for creating a policy for an S3 bucket.

该模板将 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}/*
Run Code Online (Sandbox Code Playgroud)

完成堆栈部署后,您会发现 IAM 角色已添加到存储桶中:

在此输入图像描述