amazon-web-services - 如何转换 CommaDelimitedList 参数以在 CloudFormation 中构建 ARN

标签 amazon-web-services aws-cloudformation

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

Parameters:
  UserRoles:
    Type: CommaDelimitedList
    Default: ""

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

        Principal:
          AWS:
            - !Join
              - ''
              - - 'arn:aws:iam::'
                - !Ref 'AWS::AccountId'
                - ':role/'
                - !Ref UserRole

但现在我想对数量可变的角色执行此操作。因此,我需要在字符串列表上使用某种“Fn::Map”函数,以便将角色名称转换为 Arns。

这可能吗?

最佳答案

使用 CloudFormation native 构造没有立即解决方案,但您可以使用宏构建一个解决方案。

您可以在下面找到完整的示例。总之,该解决方案有两个组成部分:

  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

关于amazon-web-services - 如何转换 CommaDelimitedList 参数以在 CloudFormation 中构建 ARN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50600339/

相关文章:

amazon-s3 - 在AWS Cloudformation中如何在s3存储桶策略中的NotIpAddress条件中使用多个if语句

amazon-web-services - 如何在 SAM 模板中添加自定义名称 Lambda 函数、API 网关和阶段名称

amazon-ec2 - AWS弹性负载均衡器和多个可用区

amazon-web-services - 如何在 AWS CDK 中指定 `CodeBuildAction` 中的区域?

amazon-web-services - 如何使用lambda将s3中的最新代码部署到lambda函数

aws-cloudformation - Terraform 资源弹性负载均衡器 - 减少 ConnectionDrainingPolicy 超时

amazon-web-services - AWS Glue Crawler 可以处理同一文件夹中的不同文件类型吗?

amazon-web-services - aws api网关测试和curl中请求正文的区别

amazon-web-services - DynamoDB 扫描最终一致性与 GSI 查询最终一致性

amazon-ec2 - AWS : Start EC2 Instance with Cloudformation and encrypt BlockDevices with specific KMS Key