【AWS】CodeBuild で パラメータストア / Secrets Manager を使う

■ はじめに

https://dk521123.hatenablog.com/entry/2020/01/31/231636

で取り上げたパラメータストア / Secrets Managerを CodeBuild 上で使う

公式サイト
https://docs.aws.amazon.com/ja_jp/codebuild/latest/userguide/build-spec-ref.html#build-spec-ref-example

■ パラメータストアの場合

* PASSWORD: 【SSMパラメータストアの名前】
  (今回「/stg/rds/password」) <= 名前を階層的に表現
  Type : Parameter

* buildspec.yml では「parameter-store」を使う

サンプル : buildspec.yml

version: 0.2

env:
  parameter-store:
    # key: key-name
    PASSWORD: /stg/rds/password

phases:
  install:
    commands:
      - echo Entered the pre_build phase...
      - echo Password is ${PASSWORD} > output.txt

■ Secrets Managerの場合

* 「secrets-manager」を使う

https://docs.aws.amazon.com/ja_jp/codebuild/latest/userguide/sample-private-registry.html
https://docs.aws.amazon.com/ja_jp/codebuild/latest/userguide/build-spec-ref.html#secrets-manager-build-spec
サンプル : buildspec.yml

version: 0.2

env:
  secrets-manager:
    # key: secret-id:json-key:version-stage:version-id
    PASSWORD: secret-id:json-key:version-stage:version-id

phases:
  install:
    commands:
      - echo Entered the pre_build phase...
      - echo Password is ${PASSWORD} > output.txt

■ 使用上の注意

【1】echo などでデバッグログ出力してもマスキングされる
【2】「parameter-store」「secrets-manager」では、動的に値を切り替えることはできない

【1】echo などでデバッグログ出力してもマスキングされる

echo "PASSWARD = ${PASSWORD}" # 「PASSWARD = ***」ってなる

https://docs.aws.amazon.com/ja_jp/codebuild/latest/userguide/getting-started-cli-build-log.html

より抜粋
~~~~
機密情報を保護するために、CodeBuild ログでは次の情報は非表示になっています。
パラメータストアを使用して指定された文字列。
AWS Secrets Manager を使用して指定された文字列。
~~~~

【2】「parameter-store」「secrets-manager」では、動的に値を切り替えることはできない

https://stackoverflow.com/questions/50451090/how-to-use-dynamic-key-for-parameter-store-in-aws-codebuild-spec-file

にある通り、以下の「できない例」のような動的な変更をする書き方はできない

できない例

  parameter-store:
    # key: key-name
    PASSWORD: /${STAGE}/rds/password  # これはできない

対応策

AWS CLI + jq コマンド や boto3 APIを利用する

以下の関連記事を参照のこと

機密データの管理 ~ パラメータストア 編 ~
https://dk521123.hatenablog.com/entry/2020/01/31/231636
機密データの管理 ~ Secrets Manager 編 ~
https://dk521123.hatenablog.com/entry/2020/03/12/220717
jq コマンド ~ コマンドで JSON を扱う ~
https://dk521123.hatenablog.com/entry/2020/02/01/000000

参考文献

https://dev.classmethod.jp/cloud/codebuild-env/

関連記事

CodeBuild ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2020/01/21/221122
CodeBuildに flake8 を組み込む
https://dk521123.hatenablog.com/entry/2020/02/17/220545
機密データの管理 ~ パラメータストア 編 ~
https://dk521123.hatenablog.com/entry/2020/01/31/231636
機密データの管理 ~ Secrets Manager 編 ~
https://dk521123.hatenablog.com/entry/2020/03/12/220717
機密データの管理 ~ Secrets Manager / boto3 編 ~
https://dk521123.hatenablog.com/entry/2021/10/05/105550
jq コマンド ~ コマンドで JSON を扱う ~
https://dk521123.hatenablog.com/entry/2020/02/01/000000