Bake 中的運算式評估

HCL 格式的 Bake 檔案支援運算式評估,讓您可以執行算術運算、有條件地設定值等等。

算術運算

您可以在運算式中執行算術運算。以下範例顯示如何將兩個數字相乘。

docker-bake.hcl
sum = 7*6

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

使用 --print 旗標列印 Bake 檔案會顯示已評估的 answer 建置引數值。

$ docker buildx bake --print app
{
  "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
{
  "group": {
    "default": {
      "targets": ["default"]
    }
  },
  "target": {
    "webapp": {
      "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 檔案會顯示已評估的 v1v2 建置引數值。

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