函式

HCL 函式非常適合當你需要以比簡單連線或插值更復雜的方式操作構建配置中的值時。

標準庫

Bake 內建支援標準庫函式

以下示例展示了 `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"]
    }
  }
}