'serverless CLI --stage param does not passed to "provider.stage"

I have the following serverless.yml file content

custom:
  alarms:
    - functionErrors
    - functionThrottles
  myStage: ${opt:stage, self:provider.stage}
  daas-aa-maturity-model-env-stage: !Join
    - '-'
    - - ${self:service}
      - ${self:custom.myStage}
      - ${self:provider.region}
  scripts:
    hooks:
      'deploy:finalize': serverless invoke -f copyGlueScripts
provider:
  name: aws
  lambdaHashingVersion: "20201221"
  managedPolicyArns:
    - 'arn:aws:iam::aws:policy/service-role/AWSGlueServiceRole'
    - ${self:provider.environment.GLUE_JOB_POLICY_ARN}
    ...

when I deploy using

serverless deploy --aws-profile "${PROFILE_NAME}" --stage nonprod && \
sleep 10 && \
sls s3deploy --profile "${PROFILE_NAME}" --stage nonprod

it generates a file .serverless/serverless-state.json which has the following values

    "provider": {
      ...
      "stage": "dev",

which runs into error when invoking a lambda with a "dev" in its name. Isn't that the "stage" supposed to be "nonprod" in my case?

If I do something like

provider:
  stage: ${opt:stage}

in serverless.yml, it gets the following error:

  ServerlessError: Cannot resolve serverless.yml: Variables resolution errored with:
    - Cannot resolve variable at "provider.stage": Value not found at "opt" source

The workaround is to specify nonprod specifically in provider:

provider:
  stage: nonprod
  name: aws

But we frequently deploy the service to different env such as dev, nonprod or prod. We would like this to be automated.

Can anyone help? Thanks!



Solution 1:[1]

You can do something like this

service: your service

custom:
  alarms:
    nonprod: alarm1
    dev: alarm2

provider:
    name: aws
    runtime: nodejs8.10
    stage: ${opt:stage, 'dev'}

functions: 
    something:
    handler: handler.scheduledUpdater
    
    someoperation: ${self:provider.stage}

sls deploy --stage nonprod otherwise it will default to dev ${opt:stage, 'dev'} takes the value passed from command line --stage option. In this case prod. If no option is passed dev is taken as default.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jatin Mehrotra