我正在尝试为几台服务器生成随机主机名。但是,在运行 terraform apply 时,我收到一条错误消息“错误:循环: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应该能够成功应用您的配置。