はじめに
久しぶりに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を修正して再度デプロイ。
ひとまず管理画面上から設定してみる。
saveしたら警告出たけどとりあえず無視。
コンソールから実行。
$ 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で設定した値に変わりました。
管理画面を見てみると、
こっちも変わってますね。
その他
- 環境変数の数に制限はない
- でもトータルのサイズは4KBまで(KMS使ってるから)