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

问题描述

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

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

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

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

这能做到吗?

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

调用 ValidateTemplate 时发生错误 (ValidationError) 操作:模板格式错误:未解决的资源依赖关系 [crm-${Environment}-register] 在模板的资源块中

解决方法

Ref 不能跨堆栈工作。假设您使用的是相同的帐户和地区,那么您必须使用 ExportImporValue 函数。

因此,在您的第一个堆栈中,您将拥有:

  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'

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...