1
votes

Question

  • What is the correct way to get the output of a cloudformation stack in a serverless.yml file without hardcoding the stack name?

Steps

I have a serverless.yml file where I import a cloudformation template to create an ElastiCache cluster.

When I try to do so, I get this error:

  Serverless Error ---------------------------------------

  Invalid variable reference syntax for variable AWS::StackName. You can only reference env vars, options, & files. You can check our docs for more info.


In my file I'd like to expose as an environment variable the ElastiCacheAddress output from the cloudformation stack. I am using the serverless pseudo-parameters plugin to get the output:

# Here is where I try to reference the CF output value
service: hello-world

provider:
  name: aws
  # ...
  environment:
    cacheUrl: ${cf:#{AWS::StackName}.ElastiCacheAddress}

# Reference to the CF template
resources: 
  - '${file(./cf/cf-elasticache.yml)}'

The CF template is the one from the AWS Samples GitHub repository.

The snippet with the output is here:

  ElastiCacheAddress:
    Description: ElastiCache endpoint address
    Value: !If [ IsRedis, !GetAtt ElastiCacheCluster.RedisEndpoint.Address, !GetAtt ElastiCacheCluster.ConfigurationEndpoint.Address]
    Export:
      Name: !Sub ${AWS::StackName}-ElastiCacheAddress
1
is the resource "ElastiCacheAddress" contained within an Output section? You need to declare the output section before you can actually reference an output resourcepkarfs
Hi @pkarfs. Yes, the ElastiCacheAddress is in the output section of the CF template. Here's the entire file. github.com/aws-samples/startup-kit-templates/blob/master/…Pablo

1 Answers

0
votes

You can use a workaround to get your way through these syntax caveats. In this case, I would suggest you to create a custom node to set variables you would want to reuse. You can then reference these variables using Serverless Framework syntax only, to avoid that error, like so:

# Here is where I try to reference the CF output value
service: hello-world

custom:
  stackName:'#{AWS::StackName}'

provider:
  name: aws
  # ...
  environment:
    cacheUrl: ${cf:${self:custom.stackName}.ElastiCacheAddress}

# Reference to the CF template
resources: 
  - '${file(./cf/cf-elasticache.yml)}'