函数

当您需要以比简单拼接或插值更复杂的方式处理构建配置中的值时,HCL 函数非常有用。

标准库

Bake 内置支持 go-cty 标准库函数。以下示例展示了 add 函数。

docker-bake.hcl
variable "TAG" {
  default = "latest"
}

group "default" {
  targets = ["webapp"]
}

target "webapp" {
  args = {
    buildno = "${add(123, 1)}"
  }
}
$ docker buildx bake --print webapp
{
  "group": {
    "default": {
      "targets": ["webapp"]
    }
  },
  "target": {
    "webapp": {
      "context": ".",
      "dockerfile": "Dockerfile",
      "args": {
        "buildno": "124"
      }
    }
  }
}

用户定义函数

如果内置标准库函数不能满足您的需求,您可以创建 用户定义函数 来实现您想要的功能。

以下示例定义了一个 increment 函数。

docker-bake.hcl
function "increment" {
  params = [number]
  result = number + 1
}

group "default" {
  targets = ["webapp"]
}

target "webapp" {
  args = {
    buildno = "${increment(123)}"
  }
}
$ docker buildx bake --print webapp
{
  "group": {
    "default": {
      "targets": ["webapp"]
    }
  },
  "target": {
    "webapp": {
      "context": ".",
      "dockerfile": "Dockerfile",
      "args": {
        "buildno": "124"
      }
    }
  }
}

函数中的变量

您可以在函数内部引用变量和标准库函数。

您不能在其他函数中引用用户定义函数。

以下示例在自定义函数中使用了全局变量 (REPO)。

docker-bake.hcl
# docker-bake.hcl
variable "REPO" {
  default = "user/repo"
}

function "tag" {
  params = [tag]
  result = ["${REPO}:${tag}"]
}

target "webapp" {
  tags = tag("v1")
}

使用 --print 标志打印 Bake 文件会显示 tag 函数如何使用 REPO 的值来设置标签的前缀。

$ docker buildx bake --print webapp
{
  "group": {
    "default": {
      "targets": ["webapp"]
    }
  },
  "target": {
    "webapp": {
      "context": ".",
      "dockerfile": "Dockerfile",
      "tags": ["user/repo:v1"]
    }
  }
}
页面选项