Julien
Julien

Reputation: 5759

Setting "local" stage env variable in Serverless v1.x

In the Serverless 1.x framework, you set environment variables in the serverless.yml file at the service root. I'm trying to set the STAGE variable that corresponds with the stage that the service is running in. It's easy for dev and prod, like so:

provider:
  name: aws
  ...
  stage: dev
  environment:
    STAGE: ${opt:stage, self:provider.stage}

This means that if --stage is explicitly defined, then the env variable uses that. If it's not, it uses the default dev.

When I use sls invoke local however, the default stage will be dev and that's not correct. What's the best way to get the stage to be local when invoking locally?

Upvotes: 1

Views: 512

Answers (1)

Julien
Julien

Reputation: 5759

The obvious solution is adding -s local to the command. This was starting to get too verbose for my liking, however, and it also increases the probability of accidentally deploying to a new stage called local which is obviously undesirable.

So, I created this helper bash function:

# Invoke serverless service
invoke() { 
    if [ "${1}" == "local" ]; then
        stage="local -s local"
    else
        stage="-s ${1}"
    fi

    payloads_dir="tests/payloads/"
    if [ -z $3 ]; then
        payload="${payloads_dir}${2}/default.json"
    else
        payload="${payloads_dir}${2}/${3}.json"
    fi

    if [ ! -f "${payload}" ]; then
        echo $payload
        echo "Payload does not exist."
        return 1
    fi

    time --format='%e seconds' serverless invoke $stage -f $2 -p $payload
}

Usage: $ invoke stage function_name [payload_name]

Examples:

$ invoke local myFunction

will invoke the function locally with the payload at tests/payloads/myFunction/default.json while applying the local stage env.

$ invoke dev myFunction my_payload

will invoke the deployed function with stage dev and payload tests/payloads/myFunction/my_payload.json (the stage env will be correct if the deployed service has the appropriate serverless.yml file).

This is clearly an opniniated implementation, but feel free to modify it to your liking!

Upvotes: 1

Related Questions