Joey Yi Zhao
Joey Yi Zhao

Reputation: 42500

How can I ref a variable in ImportValue in cloudformation?

I have a cloudformation template and need to import a value based on passed in parameter. Below is the code. But I can't combine !ImportValue and !Ref. How can I use the EnvironmentName in ImportValue function?

Parameters:

    EnvironmentName:
        Description: An environment name 
        Type: String

...

VpcConfig:
        SecurityGroupIds:
          - !ImportValue # how can I reference EnvironmentName
...

Upvotes: 2

Views: 4208

Answers (2)

Balu Vyamajala
Balu Vyamajala

Reputation: 10333

Lets say Environment is a Parameter in both templates

Security Group in Template 1:

MySecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
        GroupName: !Sub 'My Group - ${Environment}'
        GroupDescription: 'my group'
        SecurityGroupIngress:
            - IpProtocol: 'icmp'
              FromPort: '-1'
              ToPort: '-1'
              CidrIp: '0.0.0.0/0'

Exported from Template 1:

MySecurityGroup:
    Description: 'Security Group Test'
    Value: !Ref 'MySecurityGroup'
    Export:
        Name: !Sub 'MySecurityGroup-${Environment}'

Imported as

VpcConfig:
    SecurityGroupIds:
                - Fn::ImportValue: !Sub MySecurityGroup-${Environment}

Upvotes: 2

Marcin
Marcin

Reputation: 238249

As shown in the AWS docs you can use ImportValue with Sub to achieve what you want:

VpcConfig:
        SecurityGroupIds:
          - Fn::ImportValue: 
              !Sub "${EnvironmentName}"

You may need to adjust indentations to match your template.

Upvotes: 2

Related Questions