如何在Terraform Azure Local-Exe Provisioner中访问私有IP?

时间:2020-02-24 14:04:06

标签: terraform terraform-provider-azure

我具有下面的terrafrom代码,可以使用azure创建VM,并且我想通过local-exec提供程序执行命令

resource "azurerm_resource_group" "resource_gp" {
    name     =  var.azurerm_resource_group
    location =  var.azurerm_location
}

resource "azurerm_virtual_machine" "vm" {
  count                   = var.azure_vm_count
  name                    = var.azurerm_vm_name
  location                = azurerm_resource_group.resource_gp.location
  resource_group_name     = azurerm_resource_group.resource_gp.name
  network_interface_ids   = [azurerm_network_interface.nic.id]
  vm_size                 = var.azurerm_vm_size

  storage_os_disk {
    name              = "${var.azurerm_vm_name}-osdisk"
    caching           = "ReadWrite"
    create_option     = "FromImage"
    managed_disk_type = var.azurerm_vm_managed_disk_type
    disk_size_gb      = var.azurerm_vm_disk_size
  }

  storage_data_disk {
    name              = "${var.azurerm_vm_name}-datadisk"
    create_option     = "Empty"
    caching           = "ReadWrite"
    lun               = 1
    disk_size_gb      = var.azurerm_vm_disk_size
  }

  storage_image_reference {
    id = var.azurerm_image_id
  }

  os_profile {
    computer_name  = var.azurerm_vm_name
    admin_username = var.azurerm_vm_username
    admin_password = var.azurerm_vm_password
  }
  os_profile_linux_config {
    disable_password_authentication = false
  }
  provisioner "local-exec" {
    command = "echo ${self.private_ip} >> /tmp/privateip" 
  }  

}
resource "azurerm_network_interface" "nic" {
  name                = "${var.azurerm_vm_name}-nic"
  location            = azurerm_resource_group.resource_gp.location
  resource_group_name = azurerm_resource_group.resource_gp.name

  ip_configuration {
    name                            = "${var.azurerm_vm_name}-nic-config"
    subnet_id                       = var.azurerm_vnet_subnet_id
    private_ip_address_allocation   = "dynamic"
  }
}

执行代码时出现以下错误

Error: Unsupported attribute

  on main.tf line 69, in resource "azurerm_network_interface" "nic":
  69:     command = "echo ${self.private_ip} >> /tmp/privateip"

This object has no argument, nested block, or exported attribute named
"private_ip".

我正在尝试的命令是

terraform init
terraform plan -out terraform.state
terraform apply terraform.state

有人知道我在做什么错吗?如何在local-exec提供者内部访问私有IP?

1 个答案:

答案 0 :(得分:0)

如果只需要获取NIC的专用Ip,则需要访问NIC属性:

azurerm_network_interface.nic.private_ip_address