首页 > 解决方案 > packer hcl2 如何在 -var-file 或替代模式中使用本地变量

问题描述

在我的原始 json for packer 中,很容易组装引用其他变量的变量。现在打包程序建议使用 hcl2,我想知道如何使用这种模式(或 hcl2 中的反模式)。

基本运行是

packer build -var-file ubuntu.json template.json
packer build -var-file fedora.json template.json

使用 -var-file 包含不同的“boot_command”变量,该变量由内部变量组装而成。 示例有伪代码,只是为了显示问题并避免显示长行

{
  "boot_command": "ubuntu <esc><esc><wait>< preseed/url=http://{{ .HTTPIP }}:{{ .HTTPPort }}"
}

{
  "boot_command": "fedora <esc><esc><wait>< url=http://{{ .HTTPIP }}:{{ .HTTPPort }}"
}

我已将所有这些转换为 hcl。

packer build -var-file fedora.pkr.hcl template.pkr.hcl
packer build -var-file fedora.pkr.hcl template.pkr.hcl

当它在 hcl 中尝试这样做时,它不允许我分配包含变量的字符串。错误消息有些神秘“此处不允许使用块”。

locals {
  boot_command = [ "ubuntu <esc><esc><wait>< preseed/url=http://{{ .HTTPIP }}:{{ .HTTPPort }}"]
}

我想知道这是如何在 hcl2 中正确完成的,因为当我将 locals 部分按如下方式放入 template.pkr.hcl 时,它可以工作,但现在我想知道如何从“ubuntu”切换到“fedora”不是 "if ubuntu" 那么这个 boot_command 内容然后是另一个 "boot_command" 内容,因为键的顺序当然与 fedora 不同

我将如何在 hcl2 中正确执行此操作,或者我需要维护 template.pkr.hcl 的两个副本只是为了具有不同的 boot_commands 的结果?

标签: packerhcl

解决方案


推荐阅读