如何创建一个条件,只允许在同一 CloudFormation 堆栈中创建的资源承担 IAM 角色?

How to create a condition which allows only resources created in the same CloudFormation stack to assume IAM role?

我正在创建一个 CloudFormation 堆栈,其中有一个 CodeBuild 和一个 IAM 角色作为资源。我想知道是否有条件只允许在同一堆栈中创建的资源承担该角色。

目前,我的堆栈是这样定义的:

  CodeBuildProjectIAMRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: codebuild.amazonaws.com
            Action: sts:AssumeRole

  CodeBuildProject:
    Type: AWS::CodeBuild::Project

问题是任何CodeBuild项目都可以承担上面的角色。

当我尝试添加一个条件,指定只有具有 aws:cloudformation:stack-name 相同堆栈名称的主体才能担任该角色时:

  CodeBuildProjectIAMRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: codebuild.amazonaws.com
            Action: sts:AssumeRole
            Condition:
              StringEquals:
                aws:PrincipalTag/aws:cloudformation:stack-name: !Ref 'AWS::StackName'

,我得到这个错误:

Condition can contain only one colon. (Service: AmazonIdentityManagement; Status Code: 400; Error Code: MalformedPolicyDocument)

基于 these docs 我不相信你这次尝试做的事情是可能的。

具体来说:

You cannot limit permissions to pass a role based on tags attached to that role using the ResourceTag/key-name condition key