【问题标题】:terraform multiple value outputterraform 多值输出
【发布时间】:2022-01-09 06:50:35
【问题描述】:

我使用 Terraform(TF) 创建多个 Digital Ocean Droplet resource (VM),并通过 remote-exec 配置程序从 TF 公共资源中设置每个 VM random string password

resource "digitalocean_droplet" "testvm" {
  count    = var.count_of_droplets
  image    = "ubuntu-20-04-x64"
  name     = "testvm-${count.index}"
  region   = "nyc3"
  size     = "s-1vcpu-1gb"
  ssh_keys = [data.digitalocean_ssh_keys.keys.ssh_keys[0].id]
  provisioner "remote-exec" {

    connection {
      type        = "ssh"
      user        = "root"
      private_key = file("${var.my_ssh_private_key}")
      host        = self.ipv4_address
    }
    inline = [
      "echo '${var.os_user}:${random_string.password[count.index].result}' | sudo chpasswd",
      "sed -i '/PermitRootLogin/c PermitRootLogin yes' /etc/ssh/sshd_config",
      "systemctl restart sshd"
    ]
  }
  tags = ["dev"]
}

和随机密码生成器:

resource "random_string" "password" {
  count            = var.count_of_droplets
  length           = 16
  special          = true
  override_special = "_%@"
}

我通过 Terraform 输出为每个创建的带有 VM 名称的 VM 打印公共 ip:

output "droplet_ip_addresses" {
  value =    {
      for droplet in digitalocean_droplet.testvm :
      droplet.name => droplet.ipv4_address
    }
}

输出:

droplet_ip_addresses = {
   - testvm-0 = "1.1.1.1"
   - testvm-1 = "2.2.2.2"
}

如何在上面的输出中添加生成的密码?喜欢:

droplets_data = {
   - testvm-0 = "1.1.1.1" = "5j1dYBZzqDd30yhJ"
   - testvm-1 = "2.2.2.2" = "6R%wj4zebwd9FiAt"
}

【问题讨论】:

    标签: terraform digital-ocean


    【解决方案1】:

    由于通过count 创建的资源会生成一个对象列表,因此您可以使用两个资源列表的索引将它们映射在一起。

    类似

    output "droplets_data" {
      value = {
        for index, droplet in digitalocean_droplet.testvm :
          droplet.name => "'${droplet.ipv4_address}' = '${random_string.password[index].result}'"
      }
    }
    

    会为您输出如下所示的内容:

    droplets_data = {
      "testvm-0" = "'1.1.1.1' = 'KIUNOQ9YOtCk2aZQ'"
      "testvm-1" = "'2.2.2.2' = 'aTPOtb4%RCcfNo@R'"
    }
    

    不过,更简洁的方法是创建具有ippassword 属性的对象。

    类似:

    output "droplets_data" {
      value = {
        for index, droplet in digitalocean_droplet.testvm :
          droplet.name => {
            ip = droplet.ipv4_address
            password = random_string.password[index].result
          }
      }
    }
    

    这将产生:

    droplets_data = {
      "testvm-0" = {
        "ip" = "1.1.1.1"
        "password" = "KIUNOQ9YOtCk2aZQ"
      }
      "testvm-1" = {
        "ip" = "2.2.2.2"
        "password" = "aTPOtb4%RCcfNo@R"
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-01-01
      • 2017-12-24
      • 2023-01-24
      • 2020-12-07
      • 2021-03-31
      • 1970-01-01
      • 2019-12-12
      • 2021-02-12
      • 2022-01-18
      相关资源
      最近更新 更多