Terraform 中的 random_pet:錯誤:循環:

Terraform 中的 random_pet:錯誤:循環:

我正在嘗試為幾個伺服器生成隨機主機名稱。但是,當執行 terraform apply 時,我收到錯誤訊息“Error: Cycle: random_pet.swm01_managers, hcloud_server.swm01_managers”

這就是我正在嘗試做的事情:

variable "swm01_managers_count" {
  default = 5
}

# ─── CREATE RANDOM SERVER HOSTNAMES ─────────────────────────────────────────────

resource "random_pet" "swm01_managers" {
  count = "${var.swm01_managers_count}"
  keepers = {
    id = "${hcloud_server.swm01_managers[count.index].id}"
  }
}

# ─── CREATE DOCKER SWARM MANAGER NODES ──────────────────────────────────────────

resource "hcloud_server" "swm01_managers" {
  count = "${var.swm01_managers_count}"

  name = "${random_pet.swm01_managers[count.index]}"
  image = "ubuntu-18.04"
  server_type = "cx11"
  ssh_keys = "${var.ssh_keys}"
  labels = {
    "env" = "prd"
    "docker_swarm_role" = "manager"
  }

}

這是我收到的錯誤:

terraform apply --var-file=prd/prd.tfvars

Error: Cycle: random_pet.swm01_managers, hcloud_server.swm01_managers

答案1

variable "swm01_managers_count" {
  default = 5
}

# ─── CREATE DOCKER SWARM MANAGER NODES ──────────────────────────────────────────

resource "hcloud_server" "swm01_managers" {
  count = var.swm01_managers_count

  name        = random_pet.swm01_managers[count.index].id
  image       = "ubuntu-18.04"
  server_type = "cx11"
  ssh_keys    = var.ssh_keys
  labels = {
    "env"              = "prd"
    "docker_swarm_role" = "manager"
  }
}

# ─── CREATE RANDOM SERVER HOSTNAMES ─────────────────────────────────────────────

resource "random_pet" "swm01_managers" {
  count = var.swm01_managers_count
  keepers = {
    id = hcloud_server.swm01_managers[count.index].id
  }

  # Add the depends_on attribute to explicitly set the dependency on hcloud_server.swm01_managers
  depends_on = [hcloud_server.swm01_managers]
}

透過將depends_on = [hcloud_server.swm01_managers]新增至random_pet資源,您可以通知Terraform必須在建立hcloud_server.swm01_managers資源之後建立random_pet資源。這將解決循環依賴問題,並且 Terraform 應該能夠成功應用您的配置。

相關內容