How to use Cloudformation functions (i.e. Fn::Join) to populate a string variable?

Hey all,

I have a need to export some of my CloudFormation Outputs to an environment file that will be read by my Frontend application. I’m doing this by using a script that takes the environment variables as input and saves them to a file on the frontend path using the serverless-scriptable-plugin plugin.

In order to do that, I need to create string variables in my serverless.yml file that rely on CF functions. Here’s a simple example:

custom:
    apiEndpoint:
        Fn::Join:
        - ""
        - "https://"
        - Ref: "ApiGatewayRestApi"
        - ".execute-api."
        - ${self:provider.region}.
        - Ref: "AWS::URLSuffix"
        - ${self:provider.stage}

    globalFrontendEnv: VUE_APP_API = ${self:custom.apiEndpoint}

However, I’m getting the “Trying to populate non string value into a string for variable ${self:custom.apiEndpoint}” error. I imagine this is happening because the functions are not resolved until CloudFormation kicks in.

I could potentially solve this issue using the ${cf:<stackname>.<exportedvariable>} pattern but that would only work for after I initially deploy the stack for the first time because the stack has to exist in the first place.

Is there a way I could solve this problem?

I think the correct syntax for the apiEndpoint is

custom:
    apiEndpoint:
        Fn::Join:
        - ""
        - - "https://"
          - Ref: "ApiGatewayRestApi"
          - ".execute-api."
          - ${self:provider.region}.
          - Ref: "AWS::URLSuffix"
          - ${self:provider.stage}
  globalFrontendEnv:

This will only be resolved during the CloudFormation deployment so the only way I could see this working is if you store the value as an stack output then have another script read the output for your front end application.

1 Like

Yeah, I was hoping I could skip having to create a script to parse the CloudFormation file.
Thanks, @buggy

Just to be clear, parsing the CloudFormation template won’t help. You need to look at the outputs from the stack after deployment.