概要
6/26 にTerraform ver1.9.0がリリースされました。 https://github.com/hashicorp/terraform/releases
新機能:
- Input variable validation rules can refer to other objects
variable
ブロック内に記載するvalidation
ブロックについて、今までは他の変数を入れられなかったが、1.9からは他の変数の参照が可能になった。- 以下の記事が参考になります。
- templatestring function
- templatefile functionと似てますが、templatefileは
templatefile(path, vars)
のように、テンプレート文字列をfileとして渡すことができるのに対し、templatestringはtemplatestring(ref, vars)
であり、モジュール内の別の場所で定義されたオブジェクトを参照し、引数を付けてレンダリングすることができます。
- templatefile functionと似てますが、templatefileは
本記事ではtemplatestringについて記載します。
templatestringを試す
の前に、templatefileを見てみます。
テンプレートファイルを用意します。
backends.tftpl
%{ for addr in ip_addrs ~} backend ${addr}:${port} %{ endfor ~}
templatefile
で上記のテンプレートファイルに引数を渡します。
% terraform console > templatefile("${path.module}/backends.tftpl", { port = 8080, ip_addrs = ["10.0.0.1", "10.0.0.2"] }) <<EOT backend 10.0.0.1:8080 backend 10.0.0.2:8080 EOT >
一方、templatestring
は前述の通り、モジュール内の別オブジェクトのテンプレート文字列を参照します。
あらかじめ、s3に以下のファイルを格納します。
testtffile
"Hello, ${name}!"
main.tf
data "aws_s3_object" "example" { bucket = "test-tf-190" key = "testtffile" } output "example" { value = templatestring(data.aws_s3_object.example.body, { name = var.name }) } variable "name" { type = string description = "The name of the example" default = "terraform version 1.9.0" }
terraform planするとaws_s3_object.example.body(=testtffileの内容のテンプレート文字列)にvar.nameが入ることが分かります。
% terraform plan data.aws_s3_object.example: Reading... data.aws_s3_object.example: Read complete after 0s [id=test-tf-190/testtffile] Changes to Outputs: + example = "\"Hello, terraform version 1.9.0!\""
まとめ
オブジェクトの内容に変数を入れて、テンプレート文字列として扱うことができるようになりました。
また、場合によってはアップデートで追加された2つの機能を一緒に使うこともありそう?
templatestring
で使うvariableにvalidationを掛けて、validationには他の変数を使う、というパターン。