Elastic Beanstalk の環境変数で Secrets Manager のシークレットを使用する方法を試してみた
AWS Elastic Beanstalk now supports retrieving secrets and configuration from AWS Secrets Manager and AWS Systems Manager - AWS
上記アップデートのうち、Secrets Manager のシークレット参照を試してみました。
シークレット作成
適当なシークレットを作成しておきました。

Elastic Beanstalk 環境作成
Fetching secrets and parameters to Elastic Beanstalk environment variables - AWS Elastic Beanstalk
- EC2 インスタンスプロファイルには AdministratorAccess 権限を付与
- Node.js のサンプルアプリでデプロイ
環境作成時に環境プロパティの Source で Secrets Manager と Parameter Store を選択できるようになっていました。

Secrets Manager の場合、名前は任意の環境変数名で問題ありませんが、値にはシークレットの ARN を入力する必要があります。
For Environment variable value enter the ARN of the Systems Manager Parameter Store parameter or the Secrets Manager secret
今回は環境変数名に secret という名前を入力しました。
値には作成済みのシークレットの ARN を入力しました。
ログストリーミングもオンにしてサンプルアプリをデプロイしました。
デプロイ後に CloudTrail を確認したところ、EC2 インスタンスから GetSecretValue が実行されている記録がありました。

デプロイ時に Secrets Manager からシークレットを取得できたようです。
環境変数の参照
Node.js のサンプルアプリに以下の行を追加して再デプロイし、Elastic Beanstalk の環境変数からシークレットの値を参照してみます。
console.log(process.env.secret);
なお、各言語での環境変数の参照方法は以下のドキュメントで紹介されています。
Environment variables and other software settings - AWS Elastic Beanstalk
デプロイ後、CloudWatch Logs のロググループを確認したところ、シークレットの内容を参照、出力できていました。
Apr 1 11:05:50 ip-172-31-1-91 web[4463]:
{
"key": "value"
}
Secrets Manager の API をプログラムから呼び出さなくても Elastic Beanstalk の環境変数から参照できることを確認できました。
本アップデートにより、Secrets Manager や Parameter Store の API を明示的に呼び出す必要がなくなる分、コードの量が減る点などはメリットになりそうです。
注意点
Fetching secrets and parameters to Elastic Beanstalk environment variables - AWS Elastic Beanstalk
上記ドキュメントにベストプラクティスが記載されていたので簡潔にご紹介します。
- シークレットがローテーションされても Elastic Beanstalk 側の環境変数は更新されない
- 最新のシークレットを取得する場合は環境の更新やアプリサーバーの再起動を実施する
- Auto Scaling によるスケールアウト時には最新のシークレットを取得する
- インスタンス間でシークレットの値が異なる状況も発生し得る
- 同じ環境変数に対して 2 つの異なるシークレットを使用できるようアプリ側で対応することが推奨されている
- 環境変数名 A: シークレット 1 を参照
- 環境変数名 B: シークレット 1 を参照
まとめ
今回は Elastic Beanstalk の環境変数で Secrets Manager のシークレットを使用する方法を試してみました。
どなたかの参考になれば幸いです。
参考資料
- AWS Elastic Beanstalk now supports retrieving secrets and configuration from AWS Secrets Manager and AWS Systems Manager - AWS
- Fetching secrets and parameters to Elastic Beanstalk environment variables - AWS Elastic Beanstalk
- Tutorials and samples - AWS Elastic Beanstalk
- Environment variables and other software settings - AWS Elastic Beanstalk
Discussion