1
votes

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

1

1 Answers

2
votes

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'