Terraform引用循环资源值

时间:2017-04-20 21:13:06

标签: azure terraform

我正在尝试使用配置程序将新创建的Azure实例的公共IP地址写入文件。

我能够为一个实例做到这一点。

resource "azurerm_public_ip" "helloterraformips" {
    name = "terraformtestip"
    location = "East US"
    resource_group_name = "${azurerm_resource_group.test.name}"
    public_ip_address_allocation = "dynamic"

    tags {
        environment = "TerraformDemo"
    }
}


resource "null_resource" "ansible-provision" {
depends_on = ["azurerm_virtual_machine.master-vm"]
count = "${var.node-count}"
   provisioner "local-exec" {
    command =  "echo \"[masters]\n ansible_ssh_host=${azurerm_public_ip.helloterraformips.ip_address} \" >> /home/osboxes/ansible-kube/ansible/inventory/testinv"
  }
}

麻烦的是当我在VM创建的Terraform循环中尝试相同时,我在尝试访问它时遇到问题。

resource "azurerm_public_ip" "mysvcs-k8sip" {
  count                        = "${var.node-count}"
  name                         = "mysvcs-k8s-ip-${count.index}"
  location                     = "East US"
  resource_group_name          = "${azurerm_resource_group.mysvcs-res.name}"
  public_ip_address_allocation = "dynamic"
}

resource "null_resource" "ansible-provision" {

  provisioner "local-exec" {
    command =  "echo \"[masters]\n${element(azurerm_public_ip.mysvcs-k8sip.*.ip_address,count.index)} \" >> /home/osboxes/ansible-kube/ansible/inventory/inventory"
  }
 }

我收到此错误

资源'azurerm_public_ip.mysvcs-k8sip'没有变量'azurerm_public_ip.mysvcs-k8sip。* .ip_address'

的属性'ip_address'

我正在深入研究Terraform的语义并尝试各种各样的东西,但到目前为止它不起作用,每次迭代创建所有资源也需要时间。任何帮助或提示都非常有用。

谢谢,

1 个答案:

答案 0 :(得分:0)

我能够做到的一个解决方法就是运行“terraform apply -target = azurerm_virtual_machine.master-vm”,它首先创建VM。然后再次运行terraform apply,然后运行具有此

的供应商
resource "null_resource" "ansible-k8snodes"{
  count = "${var.node-count}"

  provisioner "local-exec" {
   command =  "echo \"\n[nodes]\n ${element(azurerm_public_ip.mysvcs-k8sip.*.ip_address,count.index+1)} ansible_ssh_user=testadmin ansible_ssh_pass=Password1234! \"  >>  /home/osboxes/ansible-kube/ansible/inventory/inventory"
  }
}

@Martin - 数不计数,没关系,每次都失败。事实上,在我的问题上面发布的单实例代码似乎只有一次,当我再次尝试它时,它没有用。谢谢你的帮助。