SAMで環境ごとに異なるパラメータを設定してみた


SAMからデプロイする際にパラメータを環境ごとに手動で設定してませんか?

設定ファイルに記載すると一発で環境に応じたパラメータが適応されます!

前提

  • SAMコマンドが使用可能な状態であること

ではさっそく

検証環境(stg)と本番環境(prd)ごとに異なるLambda名をつけてみましょう。

  • 検証環境のLambda名→stg-lambda-test
  • 本番環境のLambda名→prd-lambda-test

まず、今回使用する「template.yaml」です。

Envという変数に環境ごとに応じた値を設定します。

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  sam-app

  Sample SAM Template for sam-app

Parameters:
  Env:
    Type: String

Globals:
  Function:
    Timeout: 3

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.8
      Role: XXXXXXXXXXXXXXXXXXXXXXXXX # Lambda実行ロールのARN
      FunctionName: !Sub ${Env}-lambda-test

「template.yaml」と同じ階層に「samconfig.toml」を作成します。

[xxxxxxx@sandbox02 sam-app]$ touch samconfig.toml
[xxxxxxx@sandbox02 sam-app]$ ls -l
total 32
drwxr-xr-x 2 xxxxxxx xxxxxxx 4096 2021-04-08 17:37 events
drwxr-xr-x 2 xxxxxxx xxxxxxx 4096 2021-04-08 17:37 hello_world
-rw-r--r-- 1 xxxxxxx xxxxxxx    0 2021-04-08 17:37 __init__.py
-rw-r--r-- 1 xxxxxxx xxxxxxx 8349 2021-04-08 17:37 README.md
-rw-r--r-- 1 xxxxxxx xxxxxxx  659 2021-04-08 17:47 samconfig.toml
-rw-r--r-- 1 xxxxxxx xxxxxxx 1704 2021-04-08 17:47 template.yaml
drwxr-xr-x 4 xxxxxxx xxxxxxx 4096 2021-04-08 17:37 tests

「samconfig.toml」は、sam deployコマンドを実行する際にデフォルトで読み込まれるファイルになります。

[parameter_overrides]にパラメータを設定していきます。※複数ある場合はスペース区切り。

version = 1.0
[default]
[default.deploy]
# 検証環境用
[stg.deploy.parameters]
stack_name = "xxxxxx"  # スタック名
s3_bucket = "xxxxxx" # s3バケット名
s3_prefix = "xxxxxxx" # s3バケットのフォルダ名
region = "ap-northeast-1"
profile = "xxxxxxx" # profile名
confirm_changeset = true
capabilities = "CAPABILITY_IAM"
parameter_overrides="Env=stg"
# 本番環境用
[prd.deploy.parameters]
stack_name = "xxxxxx"
s3_bucket = "xxxxxx"
s3_prefix = "xxxxxxx"
region = "ap-northeast-1"
profile = "xxxxxxx"
confirm_changeset = true
capabilities = "CAPABILITY_IAM"
parameter_overrides="Env=prd"

あとはビルドしてデプロイするだけです!

sam deployコマンドのオプションに設定した環境を指定するだけで環境ごとに設定できます!

  • 検証環境用
  sam build
  sam deploy --config-env stg
  • 本番環境用
  sam build
  sam deploy --config-env prd

結果

検証環境、本番環境用それぞれsam deployコマンドを実行した結果です。

stg、prdの名前を持つLambdaが作成されていることがわかります。

環境に応じた可変パラメータはよくあるので外出しにすることでパラメータ変更による事故も起こりにくくなって便利ですね~

以上です。

参考

AWS SAM CLI 設定ファイル