build

原文


注意:此页面是关于 Packer 的 HCL2 模板的。 HCL2 模板最初作为 Beta 功能被 Packer 1.5 版引入。从 v1.7 开始,HCL2 支持不再处于测试阶段,并且是编写 Packer 配置的首选方式。对于稳定的旧风格配置语言,请参阅模板文档。从 v1.6.2 开始,您可以使用 hcl2_upgrade 命令将遗留的 JSON 模板转换为 HCL2 配置文件。

build 块定义了构建器的启动方式、如何用 provision 块配置镜像,以及如何在必要时使用 post-process 块处理的制品。

要在 build 块中使用构建器,您可以:

  • 定义引用了预先定义的 source 块的 sources 数组。
  • 定义 buildsource 块。我们也可以在这里设置特定字段。
# build.pkr.hcl
build {
    # use the `name` field to name a build in the logs.
    # For example this present config will display
    # "buildname.amazon-ebs.example-1" and "buildname.amazon-ebs.example-2"
    name = "buildname"

    sources = [
        # use the optional plural `sources` list to simply use a `source`
        # without changing any field.
        "source.amazon-ebs.example-1",
    ]

    source "source.amazon-ebs.example-2" {
        # Use the singular `source` block set specific fields.
        # Note that fields cannot be overwritten, in other words, you cannot
        # set the 'output' field from the top-level source block and here.
        output = "different value"
        name = "differentname"
    }

    provisioner "shell" {
        scripts = fileset(".", "scripts/{install,secure}.sh")
    }

    post-processor "shell-local" {
        inline = ["echo Hello World from ${source.type}.${source.name}"]
    }
}

可以定义顶级 source 块以配置构建器。可以在构建器部分找到可用构建器列表。

为构建命名

build 块的有一个可选的 name 字段可用于设置构建的名称。命名构建在 packer build 中的日志行前面将会有 build 块的名称作为前缀。例如:

source "null" "first-example" {
    communicator = "none"
}

source "null" "second-example" {
    communicator = "none"
}

build {
    name = "a"

    sources = [
        "sources.null.first-example",
        "sources.null.second-example",
    ]
}


build {
    sources = ["sources.null.second-example"]
}

其输出是:

> packer build ./folder
Build 'a.null.first-example' finished.
Build 'a.null.second-example' finished.
Build 'null.second-example' finished.

==> Builds finished. The artifacts of successful builds are:
--> a.null.first-example: Did not export anything. This is the null builder
--> a.null.second-example: Did not export anything. This is the null builder
--> null.second-example: Did not export anything. This is the null builder

运行特定的构建

-only/-except 标志将匹配 sourcetype.name 并“只运行”或是“不运行”匹配的 builder/source,例如对同一份配置文件使用这两个标志:

> packer build -only "*.second" ./folder
Build 'null.second-example' finished.
Build 'a.null.second-example' finished.

==> Builds finished. The artifacts of successful builds are:
--> a.null.second-example: Did not export anything. This is the null builder
--> null.second-example: Did not export anything. This is the null builder

这个例子里 a.null.first-example 就被跳过了。

注意:目前还不可能匹配命名 build 块来执行此操作,但将来会支持。所以这里的“a.*”将匹配不到任何内容。

results matching ""

    No results matching ""