我正在使用 Packer 为我的项目的 CI 管道配置 VM,该管道托管在受支持的云提供商上。我的配置脚本有点复杂,所以我需要仔细地迭代它们以使它们正确。为了省钱,我使用了本地镜像构建器,其配置器与云构建器中使用的配置器相同。这个本地镜像不会用于生产,甚至不会用于开发;它只是帮助我验证我的配置脚本(以及生成的环境)。
由于我正在测试我的配置器脚本,我想provisioner
与所有相关块共享一个build
块。但是,我一生都无法弄清楚如何做到这一点;现在,我一直在复制和粘贴我的provisioner
块。该only
字段是唯一变化的字段,因为我通常不想同时构建本地和云图像。如何在 HCL 格式的模板中使用provisioner
多个块中的一个块,以及偶尔的覆盖?build
这是我要缩小的代码(简化版本):
# Variables go here...
source "vagrant" "windows-local" {
source_path = "gusztavvargadr/visual-studio"
box_name = "build-runner-windows-local"
box_version = "v2019.0.2010"
communicator = "ssh"
# Other fields omitted for brevity
}
source "amazon-ebs" "windows" {
access_key = "${var.aws_access_key}"
ami_name = "build-runner-windows"
communicator = "winrm"
instance_type = "t2.micro"
region = "${var.aws_region}"
secret_key = "${var.aws_secret_key}"
source_ami_filter {
filters = {
name = "Windows_Server-2019-English-Full-Base-2020.11.11"
root-device-type = "ebs"
virtualization-type = "hvm"
}
most_recent = true
owners = ["amazon"]
}
# Other fields omitted for brevity
}
build {
name = "windows-aws"
sources = ["source.amazon-ebs.windows"]
provisioner "powershell" {
environment_vars = [
"AWS_ACCESS_KEY_ID=${var.aws_access_key}",
"AWS_SECRET_ACCESS_KEY=${var.aws_secret_key}",
"AWS_DEFAULT_REGION=${var.aws_region}",
"A_DOZEN_MORE_VARS=..."
]
only = ["amazon-ebs.windows"] # Note: Not the same value as in the windows-local build
scripts = [
"windows/first-script.ps1",
"windows/second-script.ps1",
"windows/cleanup.ps1"
]
}
provisioner "windows-restart" {}
}
build {
name = "windows-local"
sources = ["source.vagrant.windows-local"]
provisioner "powershell" {
environment_vars = [
"AWS_ACCESS_KEY_ID=${var.aws_access_key}",
"AWS_SECRET_ACCESS_KEY=${var.aws_secret_key}",
"AWS_DEFAULT_REGION=${var.aws_region}",
"A_DOZEN_MORE_VARS=..."
]
only = ["vagrant.windows-local"] # Note: Not the same value as in the windows-aws build
scripts = [
"windows/first-script.ps1",
"windows/second-script.ps1",
"windows/cleanup.ps1"
]
}
provisioner "windows-restart" {}
}