在 Cloudformation 模板中引用动态角色名称

Reference a dynamic role name in a Cloudformation template

在一个 Cloudformation 模板中,我创建了以下角色:

  CRMPiccoRole:
    Type: 'AWS::IAM::Role'
    Properties:
      RoleName: !Sub 'crm-${Environment}-register'

在另一个 EC2 实例的 Cloudformation 模板中,我试图将该角色附加到我的 EC2 实例,但是我不确定如何引用 dynamic 角色名称。

Resources:
  InstanceProfile:
    Type: 'AWS::IAM::InstanceProfile'
    Properties:
      Path: /
      Roles:
        - !Ref 'crm-${Environment}-register'

这可以做到吗?

当我尝试验证模板时出现错误:

An error occurred (ValidationError) when calling the ValidateTemplate operation: Template format error: Unresolved resource dependencies [crm-${Environment}-register] in the Resources block of the template

Ref 不能跨堆栈工作。假设您使用 相同的帐户和区域 ,您必须使用 Export and ImporValue 函数。

所以在你的第一个堆栈中你会:

  CRMPiccoRole:
    Type: 'AWS::IAM::Role'
    Properties:
      RoleName: !Sub 'crm-${Environment}-register'

Outputs:

   MyCRMPiccoRole:
     Value: !Ref CRMPiccoRole
     Export:
        Name: !Sub 'crm-${Environment}-register'

第二个堆栈中

Resources:
  InstanceProfile:
    Type: 'AWS::IAM::InstanceProfile'
    Properties:
      Path: /
      Roles:
        - Fn::ImportValue:
            !Sub 'crm-${Environment}-register'