Refer to variable within a variable

Hi -

I want to assign a variable in custom a value which is derived from other variables in custom.

Example of code I would like to write (note the variable syntax to avoid collisions with AWS variables):

provider:
  name: aws
  variableSyntax: "\\${{([ ~:a-zA-Z0-9._\\'\",\\-\\/\\(\\)]+?)}}"

config : ${{file(./config.${{opt:instance}}.yml)}}

custom: 
      client: ${{opt:client, self:config:client}}
      product: ${{opt:product, self:config:product}}
      region: ${{opt:region, self:config:region}}
      serviceName: ${{self:custom:client}}-${{self:custom:product}}

However, when I run serverless print it returns with no output. By process of elimination, I’ve tracked it down to the serviceName assignment, and I can make it work by replacing it with :

custom:
  serviceName: ${{opt:client, self:config:client}}-${{opt:product, self:config:product}}

That’s a bit ugly but I would have expected that I could use self:custom:client elsewhere in the serverless.yml file. However, if I use self:custom:client elsewhere I get:

 Trying to populate non string value into a string for variable ${{self:custom:client}}. Please make sure the value of the property is a string.

Is there any way to create a variable within the custom block which is initialised with another variable in the custom block? And any idea why the self:custom:client reference isn’t being dereferenced properly elsewhere?

Cheers,

Adam

Update to the above - the line :

config: config : ${{file(./config.${{opt:instance}}.yml)}}

wasn’t working, so I’ve now replaced it with statements similar to throughout:

${{opt:client, file(./config.${{opt:instance}}.yml):client}}

Which is truly ugly and not going to be nice to maintain…

I think you meant to use

serviceName: ${{self:custom.client}}-${{self:custom.product}}

instead of

serviceName: ${{self:custom:client}}-${{self:custom:product}}
2 Likes

I might have just said a somewhat naughty word!

It took me at least 5 minutes of staring at your response before I saw what the difference was!

Thankyou!

1000 internet points to buggy.

1 Like

For future readers struggling to find the actual difference - it’s using dot instead of colon (custom.x instead of custom:x).