LoginSignup
6
9

More than 5 years have passed since last update.

Serverless / AWS Lambdaの環境変数を使ってみる

Posted at

はじめに

久しぶりにServerless触ってみるかと思って、SlackのBOTを作ってみようとしたのですけど、WebhookのURLをコードに直書きしたくないなと。そしたら環境変数使えるんですね。下の記事を見ると最近サポートされたのでしょうか。

以下、ほぼ作業ログみたいな感じなのであしからず。

準備

まず、新規にserviceを作成。

$ sls create -t aws-nodejs -n env-sample
Serverless: Generating boilerplate...
 _______                             __
|   _   .-----.----.--.--.-----.----|  .-----.-----.-----.
|   |___|  -__|   _|  |  |  -__|   _|  |  -__|__ --|__ --|
|____   |_____|__|  \___/|_____|__| |__|_____|_____|_____|
|   |   |             The Serverless Application Framework
|       |                           serverless.com, v1.2.1
 -------'

Serverless: Successfully generated boilerplate for template: "aws-nodejs"

テンプレ。

handler.js
'use strict';

module.exports.hello = (event, context, callback) => {
  const response = {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Go Serverless v1.0! Your function executed successfully!',
      input: event,
    }),
  };

  callback(null, response);

  // Use this code if you don't use the http event with the LAMBDA-PROXY integration
  // callback(null, { message: 'Go Serverless v1.0! Your function executed successfully!', event });
};

今回はサクッと下記で。

handler.js
'use strict';

module.exports.hello = (event, context, callback) => {
  // Use this code if you don't use the http event with the LAMBDA-PROXY integration
  callback(null, { message: 'Go Serverless v1.0! Your function executed successfully!', event });
};

$ sls deploy -v
$ sls invoke -f hello
{
    "message": "Go Serverless v1.0! Your function executed successfully!",
    "event": {}
}

楽チンですね。

管理画面から環境変数設定

というわけで、環境変数を使ってみる。

handler.js
'use strict';

module.exports.hello = (event, context, callback) => {
  // Use this code if you don't use the http event with the LAMBDA-PROXY integration
  callback(null, { message: process.env.MESSAGE, event });
};

handler.jsを修正して再度デプロイ。
ひとまず管理画面上から設定してみる。

Screen Shot 2016-11-30 at 22.51.18.png

saveしたら警告出たけどとりあえず無視。

lambda_save_env.png

コンソールから実行。

$ sls invoke -f hello
{
    "message": "hoge",
    "event": {}
}

環境変数を参照できてる。

serverless.ymlで環境変数

次にserverlessを使っているのでserverless.ymlに記述する方法も試してみます。

serverless.yml
# you can define service wide environment variables here
  environment:
    MESSAGE: hello

これをデプロイして実行すると

$ sls invoke -f hello
{
    "message": "hello",
    "event": {}
}

serverless.ymlで設定した値に変わりました。
管理画面を見てみると、

Screen Shot 2016-11-30 at 23.24.15.png

こっちも変わってますね。

その他

  • 環境変数の数に制限はない
  • でもトータルのサイズは4KBまで(KMS使ってるから)

参考サイト

6
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
9