はじめに
この記事では TerraformでJSONやYAMLファイルに変数を埋め込んで、実行時に値を渡す方法をまとめます。
templatefile関数を使う

templatefile - Functions - Configuration Language | Terraform | HashiCorp Developer
The templatefile function reads the file at the given path and renders its
content as a template.
JSONに変数を埋め込んで値を渡すには、リソース側で templatefile関数 を利用します。
Terraformでtemplatefile関数を使うと、JSONファイルに変数を埋め込んで実行時に値を渡すことができる。
resource "aws_ecs_task_definition" "example" {
container_definitions = templatefile("./sample.json", {
name = "Hello_World"
})
// 略
}https://t.co/g9cisHgu7w— aiiro@ソフトウェア開発者 (@aiiro29) August 5, 2020
第一引数に用意しておいたJSONファイルのパスを指定し、第二引数で変数のマップを指定します。
ファイルに変数を埋め込む
JSONファイルに変数を埋め込むには、templatefile関数で設定した変数名を “${ … }” で囲みます。
ファイルに埋め込む変数は次のように書く。
[
{
"name": "${name}",
// 略
}
]— aiiro@ソフトウェア開発者 (@aiiro29) August 5, 2020
これでファイルに埋め込んだ変数に対して、リソース実行時に値を渡すことができます。