amazon-web-servicesamazon-ec2aws-cloudformationamazon-iamiaas

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


Solution

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

    Then in the second stack:

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