Terraform v1.9.0で追加されたtemplatestringを試してみる

概要

6/26 にTerraform ver1.9.0がリリースされました。 https://github.com/hashicorp/terraform/releases

新機能:

  • Input variable validation rules can refer to other objects
  • templatestring function
    • templatefile functionと似てますが、templatefileはtemplatefile(path, vars)のように、テンプレート文字列をfileとして渡すことができるのに対し、templatestringはtemplatestring(ref, vars)であり、モジュール内の別の場所で定義されたオブジェクトを参照し、引数を付けてレンダリングすることができます。

本記事では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には他の変数を使う、というパターン。