How to use ImportValue with dynamic values in cloudformation?

Viewed 13

I am trying to reference a output of a stack in another stack with ImportValue function. The output name depends on the stack name, so thought to pass the stackname and use the ImportValue and Sub/Join together but getting syntax error.

My template where the outputs are generated.

AWSTemplateFormatVersion: 2010-09-09
Description: Basic EC2 instance
Resources: #dictionary
  MyInstance: # dictionary  -----> logical name for this resource
    Type: AWS::EC2::Instance #---> type of resource
    Properties: #dictionary the set of properties to configure this resource
      ImageId: ami-0568773882d492fc8     # required
      InstanceType: t2.micro
Outputs:
  InstanceId:
    Description: EC2 Instance ID generated
    Value: !Ref MyInstance
    Export:
      Name: !Sub "${AWS::StackName}-InstanceId"
  InstanceAZ:
    Description: Instance AvailabilityZone
    Value: !GetAtt MyInstance.AvailabilityZone
    Export:
      Name: !Sub "${AWS::StackName}-InstanceAz"

My stack, where this outputs are referred. If you observer, the name of outputs above dependent on the StackName, so in the below stack, thought to expand that name by passing the stackname as parameter, but not working.

---
AWSTemplateFormatVersion: "2010-09-09"
Parameter:
  ReferenceStack:
    Description: select the previous reference stack
    Type: String
Resources:
  MountPoint:
    Type: AWS::EC2::VolumeAttachment
    Properties:
      Device: /dev/sdh     # required
      InstanceId: Fn::ImportValue:
        !Join ["-",[!Ref 'ReferenceStack',InstanceId]] # required
      VolumeId: !Ref  NewVolume    # required
  NewVolume:
    Type: AWS::EC2::Volume
    Properties:
      AvailabilityZone: Fn::ImportValue:
        !Join ["-",[!Ref 'ReferenceStack',InstanceAz]]
        #!Sub ${ReferenceStack}-InstanceAz
      Size: 1
0 Answers
Related