【问题标题】:Read an external file which contains a variable in Terraform读取包含 Terraform 中变量的外部文件
【发布时间】:2020-10-07 00:38:52
【问题描述】:

我正在使用 Terraform 部署 google_compute_instance。该实例应在创建时运行脚本。使用属性metadata_startup_script

resource "google_compute_instance" "couchbase_host" {
   ...

   metadata_startup_script = file("vm_setup.sh")
}

在哪里vm_setup.sh

program --arg ${var.my_value}

file() 提取为原始字符串,这意味着未填充变量。如何在.sh 中使用 terraform 变量?我试图避免使用 heredoc << EOF ..,因为我的脚本有点长。

【问题讨论】:

标签: terraform


【解决方案1】:

The templatefile functionthe file function 类似,它从磁盘读取给定文件,但它还将文件的内容额外解释为string template,因此您可以将外部值插入其中。

例如:

   metadata_startup_script = templatefile("${path.module}/vm_setup.sh.tmpl", {
     arg_value = var.my_value
   })

在模板文件中,您可以使用${arg_value} 将第二个参数中对象的给定值替换为templatefile


请注意,仅直接引用该值,结果不一定是有效的 shell 语法——调用者可能会将 var.my_value 设置为会被 shell 误解的内容。避免这种情况的一种方法是使用 the replace function 对值应用单引号,假设此脚本最终将由 Unix 样式的 shell(bash 等)评估:

program --arg '${replace(arg_value, "'", "'\\''")}'

如果arg_value 的值为I'm a troublemaker,那么上述模板将产生以下结果:

program --arg 'I'\''m a troublemaker'

...周围的' 引号字符和字符串中' 的特殊转义应该导致shell 按字面意思解释该值,与模块调用者提供的完全一样。

【讨论】:

    猜你喜欢
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-22
    • 2015-10-17
    相关资源
    最近更新 更多