变量值的 Heredoc 语法

tra*_*jan 5 terraform

我尝试使用 Heredoc 语法作为字符串变量的值,如下所示

variable "docker_config" {
  type = "string"
  default = <<EOF
{ "auths": { "https://index.docker.io/v1/": { "auth": "****" } } }
EOF
}
Run Code Online (Sandbox Code Playgroud)

这不会导致 Terraform 产生错误,但是当稍后在远程执行命令"echo ${var.docker_config} > /home/ubuntu/.docker/config.json"中使用该变量时,该值为空。

这是在变量中使用 Heredoc 语法的正确方法吗?

Som*_*ter 4

您可以在变量中执行heredoc,在局部变量中执行heredoc,或者您可以构造一个映射并使用jsonencode它将其转换为字符串。您也可以稍后使用其中任何一个。

\n\n

\xe2\x9c\x97 cat main.tf

\n\n
variable "test" {\n  description = "Testing heredoc"\n  default     = <<EOF\n        "max-size": "8m",\n        "min-size": "1m",\n        "count": "8",\n        "type": "string",\nEOF\n}\n\nlocals {\n  docker_config = <<EOF\n{\n  "auths": {\n    "https://index.docker.io/v1/": {\n      "auth": "****"\n    }\n  }\n}\nEOF\n\n  even_better = {\n    auths = {\n      "https://index.docker.io/v1/" = {\n        auth = "****"\n      }\n    }\n  }\n}\n\noutput "test_var" {\n  value = var.test\n}\n\noutput "test_local" {\n  value = local.docker_config\n}\n\noutput "even_better" {\n  value = jsonencode(local.even_better)\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n
$ terraform apply\n\nApply complete! Resources: 0 added, 0 changed, 0 destroyed.\n\nOutputs:\n\neven_better = {"auths":{"https://index.docker.io/v1/":{"auth":"****"}}}\ntest_local = {\n  "auths": {\n    "https://index.docker.io/v1/": {\n      "auth": "****"\n    }\n  }\n}\n\ntest_var = {\n  "auths": {\n    "https://index.docker.io/v1/": {\n      "auth": "****"\n    }\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n