ホーム > Other > How to Use Environment Variables in YAML (yml)
Other

How to Use Environment Variables in YAML (yml)

Thank you for your continued support.
This article contains advertisements that help fund our operations.

Introduction

In this article,

Error:
Cannot resolve serverless.yml: Variables resolution errored with:
  - Cannot resolve variable at "provider.environment.SLACK_SIGNING_SECRET": Value not found at "env" source,
  - Cannot resolve variable at "provider.environment.SLACK_BOT_TOKEN": Value not found at "env" source

This kind of error might be resolved.

Background

There are times when you want to put environment variables in yml when using Lambda, etc.

For example, when using SlackAPI,

serverless.yml

service: serverless-bolt-js
frameworkVersion: '3'
provider:
  name: aws
  runtime: nodejs14.x
  environment:
    SLACK_SIGNING_SECRET: ${env:SLACK_SIGNING_SECRET}
    SLACK_BOT_TOKEN: ${env:SLACK_BOT_TOKEN}
functions:
  slack:
    handler: app.handler
    events:
      - http:
          path: slack/events
          method: post
      - http:
          path: /slack/install
          method: get
      - http:
          path: /slack/user_install
          method: get
      - http:
          path: /slack/oauth_redirect
          method: get
useDotenv: true
plugins:
  - serverless-offline

You may want to use environment variables.

How to use environment variables

The above code is already configured to use environment variables.

The relevant parts are,

  environment:
    SLACK_SIGNING_SECRET: ${env:SLACK_SIGNING_SECRET}
    SLACK_BOT_TOKEN: ${env:SLACK_BOT_TOKEN}
useDotenv: true

in two places.

Create a file named .env in the project's root directory,

SLACK_SIGNING_SECRET=Enter API key here
SLACK_BOT_TOKEN=Enter API key here

and you can use it just like that.

Conclusion

I wrote this article because I found that this simple method is surprisingly hard to find when searching.

I hope it can be helpful as a reference.

Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!