[アップデート]AWS SAM CLIの設定ファイルにyaml形式が利用できるようになりました

2023.07.19

初めに

本日AWS SAM CLIのv1.91.0がリリースされました。

AWS SAM CLIの設定ファイルはsamconfig.tomlとなりtoml形式が採用されていましたが、今回のアップデート以降はyamlファイルが利用可能となります。

なお執筆時点でドキュメントには記載がないようで、英語版ドキュメントでもフォーマットの記載はtomlのみとなっております。

設定ファイルの作成

sam initでまずはプロジェクトを生成します。

対話の際の回答により内容は変動しますが今回の設定の場合は以下のようなsamconfig.tomlが生成されます。

samconfig.toml

# More information about the configuration file can be found here:
# https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html
version = 0.1

[default]
[default.global.parameters]
stack_name = "sam-app-default"

[default.build.parameters]
cached = true
parallel = true

[default.validate.parameters]
lint = true

[default.deploy.parameters]
capabilities = "CAPABILITY_IAM"
confirm_changeset = true
resolve_s3 = true

[default.package.parameters]
resolve_s3 = true

[default.sync.parameters]
watch = true

[default.local_start_api.parameters]
warm_containers = "EAGER"

[default.local_start_lambda.parameters]
warm_containers = "EAGER"

上記の内容をyamlのフォーマットで書き直す以下のようになります。

samconfig.yaml

version: 0.1
default:
  global:
    parameters:
      stack_name: sam-app-default
  build:
    parameters:
      cached: true
      parallel: true
  validate:
    parameters:
      lint: true
  deploy:
    parameters:
      capabilities: CAPABILITY_IAM
      confirm_changeset: true
      resolve_s3: true
  package:
    parameters:
      resolve_s3: true
  sync:
    parameters:
      watch: true
  local_start_api:
    parameters:
      warm_containers: EAGER
  local_start_lambda:
    parameters:
      warm_containers: EAGER

生成したプロジェクトからsamconfig.tomlを削除し上記の内容を記載したsamconfig.yamlを設置します。

$ ls sam-app-default
README.md       __init__.py     events          hello_world     samconfig.yaml  template.yaml   tests

実行

yamlの設定ファイルを読み込むために別途オプション等は不要です。

toml形式の設定ファイルが存在しない状態でsam deployを実行しましたが--guidedがなくとも正常にデプロイができました。

$ sam build --no-cached
Building codeuri: /xxxxx/sam-app-default/hello_world runtime: python3.9 metadata: {} architecture: x86_64 functions: HelloWorldFunction                                                                                                                                                                                                                                                                                                                                        
Running PythonPipBuilder:ResolveDependencies                                                                                                                                                                                                                                                                                                                                                                                                                                                    
Running PythonPipBuilder:CopySource                                                                                                                                                                                                                                                                                                                                                                                                                                                             

Build Succeeded

Built Artifacts  : .aws-sam/build
Built Template   : .aws-sam/build/template.yaml

Commands you can use next
=========================
[*] Validate SAM template: sam validate
[*] Invoke Function: sam local invoke
[*] Test Function in the Cloud: sam sync --stack-name {{stack-name}} --watch
[*] Deploy: sam deploy --guided

$ sam-app-default % sam deploy

                Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-xxxxx
                A different default S3 bucket can be set in samconfig.toml
                Or by specifying --s3-bucket explicitly.
        Uploading to xxxxx  606922 / 606922  (100.00%)

        Deploying with following values
        ===============================
        Stack name                   : sam-app-default
        Region                       : ap-northeast-1
        Confirm changeset            : True
        Disable rollback             : False
        Deployment s3 bucket         : aws-sam-cli-managed-default-samclisourcebucket-xxxxx
        Capabilities                 : ["CAPABILITY_IAM"]
        Parameter overrides          : {}
        Signing Profiles             : {}

Initiating deployment
=====================

        Uploading to xxxxx.template  558 / 558  (100.00%)


Waiting for changeset to be created..

CloudFormation stack changeset
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Operation                                                                                                               LogicalResourceId                                                                                                       ResourceType                                                                                                            Replacement                                                                                                           
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+ Add                                                                                                                   HelloWorldFunctionRole                                                                                                  AWS::IAM::Role                                                                                                          N/A                                                                                                                   
+ Add                                                                                                                   HelloWorldFunction                                                                                                      AWS::Lambda::Function                                                                                                   N/A                                                                                                                   
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


Changeset created successfully. arn:aws:cloudformation:ap-northeast-1:xxxxxx:changeSet/samcli-deployxxxx/xxxxx


Previewing CloudFormation changeset before deployment
======================================================
Deploy this changeset? [y/N]: y

2023-07-19 11:54:56 - Waiting for stack create/update to complete

CloudFormation events from stack operations (refresh every 5.0 seconds)
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ResourceStatus                                                                                                          ResourceType                                                                                                            LogicalResourceId                                                                                                       ResourceStatusReason                                                                                                  
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS                                                                                                      AWS::CloudFormation::Stack                                                                                              sam-app-default                                                                                                         User Initiated                                                                                                        
CREATE_IN_PROGRESS                                                                                                      AWS::IAM::Role                                                                                                          HelloWorldFunctionRole                                                                                                  -                                                                                                                     
CREATE_IN_PROGRESS                                                                                                      AWS::IAM::Role                                                                                                          HelloWorldFunctionRole                                                                                                  Resource creation Initiated                                                                                           
CREATE_COMPLETE                                                                                                         AWS::IAM::Role                                                                                                          HelloWorldFunctionRole                                                                                                  -                                                                                                                     
CREATE_IN_PROGRESS                                                                                                      AWS::Lambda::Function                                                                                                   HelloWorldFunction                                                                                                      -                                                                                                                     
CREATE_IN_PROGRESS                                                                                                      AWS::Lambda::Function                                                                                                   HelloWorldFunction                                                                                                      Resource creation Initiated                                                                                           
CREATE_COMPLETE                                                                                                         AWS::Lambda::Function                                                                                                   HelloWorldFunction                                                                                                      -                                                                                                                     
CREATE_COMPLETE                                                                                                         AWS::CloudFormation::Stack                                                                                              sam-app-default                                                                                                         -                                                                                                                     
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


Successfully created/updated stack - sam-app-default in ap-northeast-1

メッセージにまだsamconfig.tomlが残っていますが同ファイル名のファイルは存在しないのでyamlが読み込まれているはず...です。

guidedによる生成も対応済み

sam initによる生成では設定ファイル名の指定がない関係でyamlでの生成は未対応ですが、sam deploy--guidedでの生成は既にyamlをサポートしているようです。

指定方法としてはファイル名のサフィックスを.yamlにすれば自動的にyamlフォーマットとなります。

# 既存の設定の読み込みの影響を加味し念の為設定を削除してから実行
% rm samconfig.yaml
% sam deploy --guided

Configuring SAM deploy
======================

        Looking for config file [samconfig.toml] :  Not found

        Setting default arguments for 'sam deploy'
        =========================================
        Stack Name [sam-app]: sam-app-default-guided
        AWS Region [ap-northeast-1]: 
        #Shows you resources changes to be deployed and require a 'Y' to initiate deploy
        Confirm changes before deploy [y/N]: y
        #SAM needs permission to be able to create roles to connect to the resources in your template
        Allow SAM CLI IAM role creation [Y/n]: Y
        #Preserves the state of previously provisioned resources when an operation fails
        Disable rollback [y/N]: N
        Save arguments to configuration file [Y/n]: Y
        SAM configuration file [samconfig.toml]: samconfig.yaml
        SAM configuration environment [default]: 
...

以下のファイルが生成されます。

samconfig.toml

default:
  deploy:
    parameters:
      stack_name: sam-app-default-guided
      resolve_s3: true
      s3_prefix: sam-app-default-guided
      region: ap-northeast-1
      profile: default
      confirm_changeset: true
      capabilities: CAPABILITY_IAM
      image_repositories: []
version: 0.1

読み込みはtomlが優先される

デフォルト名として利用可能なsamconfig.tomlsamconfig.yamlを両方存在させた状態でstack_nameのパラメータをそれぞれsam-app-default-guided-tomlsam-app-default-guided-yamlとして指定しsam deployを実行してみました。

$ sam deploy
More than one samconfig file found; using samconfig.toml. To use another config file, please specify it using the '--config-file' flag.                                                                                                                                                                                                                                                                                                                                                         
...
        Deploying with following values
        ===============================
        Stack name                   : sam-app-default-guided-toml
        Region                       : ap-northeast-1
        Confirm changeset            : True
        Disable rollback             : False
        Deployment s3 bucket         : aws-sam-cli-managed-default-samclisourcebucket-xxxx
        Capabilities                 : ["CAPABILITY_IAM"]
        Parameter overrides          : {}
        Signing Profiles             : {}

どうやらこの場合はsamconfig.tomlが優先して読み込まれるようです。

複数samconfigファイルが存在しsamconfig.tomlが読み込まれている旨は記載されていますが、白字の関係で見落としがちなポイントになるかもしれないため注意しましょう。

終わりに

今回のアップデートでSAMの設定ファイルの形式の選択肢が1つ増えました。

個人的にはCloudFormation、DockerのComposeファイル、ansible等設定ファイルを書く際にはyamlフォーマットで記載するような機会が多いので使い慣れ的に非常に嬉しいアップデートです。

またSAMテンプレート自体もYAMLで記載可能なため設定関連のフォーマットを揃えることができるのはSAMだけでみても嬉しい点ではあると思います。

とはいえフォーマット程の違いでプログラミング言語のように大きく学習が必要なものではありませんので、属する環境や慣れに応じて選択いただければと思います。

備考(2023/07/20追記)

本機能とは直接関係はありませんがv1.91.0にはsam remote invokeがエラーとなり実行できないバグが含まれるためご注意ください。
当バージョン固有のバグのためv1.92.0以降にバージョンアップすることで解消します。