简体   繁体   中英

Reference a dynamic role name in a Cloudformation template

In one Cloudformation template I create the following role:

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

In another Cloudformation template for an EC2 instance I am attempting to attach that role to my EC2 instance, however I am unsure how to reference a dynamic role name.

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

Can this be done?

When I attempt to validate the template I get an error:

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 does not work across stacks. Assuming you are using same account and region , instead you have to use Export and ImporValue functions.

So in your first stack you would have:

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

Outputs:

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

In the second stack :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM