如何从下面的 terraform 代码获取 public azure VM 的 IP

How to get public IP of azure VM from the below terraform code

我有一个 terraform 代码需要检索 public 虚拟机的 ip,这是我的代码

# Create virtual machine
resource "azurerm_virtual_machine" "myterraformvm" {
    name                  = "myTerraformVM"
    location              = "Central India"
    resource_group_name   = "rg-mpg-devops-poc"
    network_interface_ids = ["/subscriptions/*************/resourceGroups/rg-mpg-devops-poc/providers/Microsoft.Network/networkInterfaces/nic-mpg-devops"]
    vm_size               = "Standard_DS1_v2"

    storage_os_disk {
        name              = "myOsDisk"
        caching           = "ReadWrite"
        create_option     = "FromImage"
        managed_disk_type = "Premium_LRS"
    }

    os_profile {
        computer_name  = "myvm"
        admin_username = "azureuser"
    }

    os_profile_linux_config {
        disable_password_authentication = true
        ssh_keys {
            path     = "/home/azureuser/.ssh/authorized_keys"
            key_data = "ssh-rsa *********************"
        }}
     boot_diagnostics {
        enabled = "true"
        storage_uri = "https://*******.blob.core.windows.net/"
    }}

这里使用的是网卡id,默认会提供public ip,有人可以帮我吗?

你会为此使用数据模块:

data "azurerm_network_interface" "test" {
  name                = "acctest-nic"
  resource_group_name = "networking"
}

会给你 NIC 对象,有 ip_configuration 块,(反过来)有 public_ip_address_id 参数,你会用它来获取 public 的数据ip:

data "azurerm_public_ip" "test" {
  name                = "name_of_public_ip"
  resource_group_name = "name_of_resource_group"
}

output "domain_name_label" {
  value = "${data.azurerm_public_ip.test.domain_name_label}"
}

output "public_ip_address" {
  value = "${data.azurerm_public_ip.test.ip_address}"
}

显然,您必须将资源 ID 解析为资源的资源 group\name,但这可以通过 split + array index

轻松完成

https://www.terraform.io/docs/providers/azurerm/d/public_ip.html
https://www.terraform.io/docs/providers/azurerm/d/network_interface.html

我试过了,但无法检索 public IP。 (很可能是飞行员失误。)

在我的例子中,我需要在后面的步骤中检索一个地址来安装 chef,这样 IP 或 FQDN 就可以了。以下是我如何度过难关:

在创建我的 public ip 时,我添加了域标签。定义机器名称时使用相同的值。

resource "azurerm_public_ip" "CSpublicip" {
    name                         = "myPublicIP"
    location                     = "eastus"
    resource_group_name          = "${azurerm_resource_group.CSgroup.name}"
    allocation_method            = "Dynamic"
    domain_name_label            = "csvm${random_integer.server.result}"

添加域标签时,Azure 会创建一个可访问的 FQDN。一旦你有了它,你就可以 use/retrieve fqdn。

output "AzurePage" {
value = "${azurerm_public_ip.CSpublicip.fqdn}"