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 變數為真,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 檔案時,會顯示 v1v2 建置引數的評估值。

$ docker buildx bake --print app
{
  "group": {
    "default": {
      "targets": ["app"]
    }
  },
  "target": {
    "app": {
      "context": ".",
      "dockerfile": "Dockerfile",
      "args": {
        "v1": "lower",
        "v2": "yes"
      }
    }
  }
}
© . This site is unofficial and not affiliated with Kubernetes or Docker Inc.