如何在CloudForm中转换CommaDlimitedList参数以构建ARN [英] How to transform CommaDelimitedList parameter to build ARNs in CloudFormation

查看:19
本文介绍了如何在CloudForm中转换CommaDlimitedList参数以构建ARN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Parameters:
  UserRoles:
    Type: CommaDelimitedList
    Default: ""
现在,我想在策略文档主体中使用这些角色。如果只有一个角色,我会这样做:

        Principal:
          AWS:
            - !Join
              - ''
              - - 'arn:aws:iam::'
                - !Ref 'AWS::AccountId'
                - ':role/'
                - !Ref UserRole
但现在我想对数量可变的角色执行此操作。因此,我需要字符串列表上的某种";fn::map";函数,用于将角色名称转换为Arn。

这可能吗?

推荐答案

使用云表单本机构造没有立即的解决方案,但是您可以使用宏来构建一个。

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

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

下面的示例解决了此处提出的直接问题,但是对于希望执行自定义字符串操作的一般读者应该很有用。


生成用于字符串操作的自定义宏

以下模板创建由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角色已添加到存储桶中:

这篇关于如何在CloudForm中转换CommaDlimitedList参数以构建ARN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆