内建代码块

原文


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

Packer - HCL2 语言包含许多可用于配置构建的内建块。块是配置的容器。

最重要的块可以分为几个主要类型:

  • builder 块包含用于创建特定镜像制品的构建器、配置器和后处理器的组合配置。
  • source 块包含构建器插件的配置。一旦定义,可以在 builder 块中使用并进一步配置源信息。
  • provisioner 块包含配置器插件的配置。provisioner 块是存在于 builder 块内部的嵌套块。
  • post-processorpost-processors 包含后处理器插件和后处理器插件序列的配置。这两个块也是存在于 builder 块内部的嵌套块。
  • variable 块包含变量的配置,这些变量可以在配置中设置默认值,也可以由用户在运行时设置。
  • locals 块包含中间变量的配置,这些中间变量可以使用 HCL 函数或数据源创建,或者由 variable 块中声明的变量组合而成。

本电子书包含每种块类型的信息。

其他块,例如 packer 块,对 Packer 进程提供了该配置文件允许运行哪个版本 Packer 执行的信息。 required_plugins 块有助于 Packer 进程了解配置文件所需要的插件来源及版本信息。

块可以在多个文件中定义,packer build folder 命令将仅使用名为 folder 的目录中的文件进行构建。

Packer 不支持用户自定义块,因此只能使用语言中内置的块。本电子书包括所有可用的内置 HCL2 块。

配置样例

# variables.pkr.hcl
variable "foo" {
    type        = string
    default     = "the default value of the `foo` variable"
    description = "description of the `foo` variable"
    sensitive   = false
    # When a variable is sensitive all string-values from that variable will be
    # obfuscated from Packer's output.
}

variable 块的文档

# locals.pkr.hcl
locals {
    # locals can be bare values like:
    wee = local.baz
    # locals can also be set with other variables :
    baz = "Foo is '${var.foo}' but not '${local.wee}'"
}

# Use the singular local block if you need to mark a local as sensitive
local "mylocal" {
  expression = "${var.secret_api_key}"
  sensitive  = true
}

locals 块的文档

# sources.pkr.hcl
source "happycloud" "foo" {
    // ...
}

source 块的文档

# 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}"]
    }
}

builder 块的文档

# datasource.pkr.hcl
data "amazon-ami" "basic-example" {
  // ...
}

data 块的文档

results matching ""

    No results matching ""