问题描述
在一个 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
不能跨堆栈工作。假设您使用的是相同的帐户和地区,那么您必须使用 Export 和 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'