DigitalOcean 液滴配置:周期错误

DigitalOcean droplet provisioning: Cycle Error

我想创建多个 droplet,同时使用远程配置器在每个 droplet 上安装一些软件。我有以下代码:

resource "digitalocean_droplet" "server" {
  for_each = var.servers

  name   = each.key
  image  = each.value.image
  size   = each.value.size
  region = each.value.region
  ssh_keys = [
    data.digitalocean_ssh_key.terraform.id
  ]
  tags = each.value.tags

  provisioner "remote-exec" {
    inline = [
      "mkdir -p  /tmp/scripts/",
    ]

    connection {
      type        = "ssh"
      user        = "root"
      private_key = file("${var.ssh_key}")
      host        = digitalocean_droplet.server[each.key].ipv4_address
    }
  }

这总是会导致以下错误:

Error: Cycle: digitalocean_droplet.server["server2"], digitalocean_droplet.server["server1"]

我理解这是指循环依赖,但是如何在每台服务器上安装软件。

正如我在评论中提到的,这里的问题是您正在创建循环依赖性,因为您是在其自己的块中通过名称引用资源。引用 [1]:

References create dependencies, and referring to a resource by name within its own block would create a dependency cycle.

要解决此问题,您可以使用特殊关键字 self 来引用正在创建的同一实例:

resource "digitalocean_droplet" "server" {
  for_each = var.servers

  provisioner "remote-exec" {
    inline = [
      "mkdir -p  /tmp/scripts/",
    ]

    connection {
      type        = "ssh"
      user        = "root"
      private_key = file("${var.ssh_key}")
      host        = self.ipv4_address # <---- here is where you would use the self keyword
    }
  }

[1] https://www.terraform.io/language/resources/provisioners/connection#the-self-object