Kanji
・クラウドエンジニア / フリーランス ・1993年生まれ ・愛媛県出身 / 東京都渋谷区在住 ・AWS歴5年 プロフィールの詳細
目次
Terraform テンプレートの Git レポジトリを分割している、もしくは、 Module を利用している場合
カスタムの Data Source を定義したい場合、 External Data Source を利用します。
external_external | Data Sources | hashicorp/external | Terraform Registry
Data Source として既存リソースの情報を取得するため、 program で Bash や Python などのスクリプトを呼び出し、実行結果として JSON 形式の文字列を出力します。
program
# !/bin/bash eval "$(jq -r '@sh "codepipeline_name_prefix=\(.codepipeline_name_prefix)"')" pipelines=$( aws codepipeline \ list-pipelines \ --query "pipelines[?starts_with(name, '"${codepipeline_name_prefix}"')].name" \ --region ap-northeast-1 \ --output json ) # ポイント result=$(cat << EOS { "names": $(echo "${pipelines}" | jq '@json') } EOS ) jq -n "$result"
# ポイント
names
| jq '@json'
# ポイントの変更前 result=$(cat << EOS { "names": $(echo "${pipelines}") } EOS ) # result 変数 { "names": [ "test-pipeline01", "test-pipeline02", "test-pipeline03", "test-pipeline04", "test-pipeline05" ] }
% terraform plan data.external.aws_codepipelines: Reading... ╷ │ Error: Unexpected External Program Results │ │ with data.external.aws_codepipelines, │ on test.tf line 2, in data "external" "aws_codepipelines": │ 2: program = ["bash", "${path.module}/ListCodePipelineNames.sh"] │ │ The data source received unexpected results after executing the program. │ │ Program output must be a JSON encoded map of string keys and string values. │ │ If the error is unclear, the output can be viewed by enabling Terraform's logging at TRACE level. │ Terraform documentation on logging: https://www.terraform.io/internals/debugging │ │ Program: /bin/bash │ Result Error: json: cannot unmarshal array into Go value of type string
# ポイントの変更前 result=$(cat << EOS { "names": $(echo "${pipelines}" | jq '@json') } EOS ) # result 変数 { "names": "[\"test-pipeline01\",\"test-pipeline02\",\"test-pipeline03\",\"test-pipeline04\",\"test-pipeline05\"]" }
data "external" "aws_codepipelines" { program = ["bash", "${path.module}/scripts/ListCodePipelineNames.sh"] query = { codepipeline_name_prefix = "test-pipeline0" } } # ポイント output aws_codepipelines_names { value = jsondecode(data.external.aws_codepipelines.result["names"]) }
scripts
ListCodePipelineNames.sh
query
codepipeline_name_prefix
jsondecode()