Bake 中的表达式评估

HCL 格式的 Bake 文件支持表达式评估,允许你执行算术运算、有条件地设置值等。

算术运算

你可以在表达式中执行算术运算。以下示例展示了如何将两个数字相乘。

docker-bake.hcl
sum = 7*6

target "default" {
  args = {
    answer = sum
  }
}

使用 `--print` 标志打印 Bake 文件将显示 `answer` 构建参数的评估值。

$ docker buildx bake --print
{
  "target": {
    "default": {
      "context": ".",
      "dockerfile": "Dockerfile",
      "args": {
        "answer": "42"
      }
    }
  }
}

三元运算符

你可以使用三元运算符有条件地注册值。

以下示例仅在变量非空时添加标签,使用了内置的 `notequal` 函数

docker-bake.hcl
variable "TAG" {}

target "default" {
  context="."
  dockerfile="Dockerfile"
  tags = [
    "my-image:latest",
    notequal("",TAG) ? "my-image:${TAG}": "",
  ]
}

在本例中,`TAG` 是一个空字符串,因此生成的构建配置仅包含硬编码的 `my-image:latest` 标签。

$ docker buildx bake --print
{
  "target": {
    "default": {
      "context": ".",
      "dockerfile": "Dockerfile",
      "tags": ["my-image:latest"]
    }
  }
}

使用变量的表达式

你可以使用带有变量的表达式有条件地设置值或执行算术运算。

以下示例使用表达式根据变量值设置值。如果变量 `FOO` 大于 5,则 `v1` 构建参数设置为 "higher",否则设置为 "lower"。如果变量 `IS_FOO` 为 true,则 `v2` 构建参数设置为 "yes",否则设置为 "no"。

docker-bake.hcl
variable "FOO" {
  default = 3
}

variable "IS_FOO" {
  default = true
}

target "app" {
  args = {
    v1 = FOO > 5 ? "higher" : "lower"
    v2 = IS_FOO ? "yes" : "no"
  }
}

使用 `--print` 标志打印 Bake 文件将显示 `v1` 和 `v2` 构建参数的评估值。

$ docker buildx bake --print app
{
  "group": {
    "default": {
      "targets": ["app"]
    }
  },
  "target": {
    "app": {
      "context": ".",
      "dockerfile": "Dockerfile",
      "args": {
        "v1": "lower",
        "v2": "yes"
      }
    }
  }
}
页面选项