0

我有一个需要检索 vm 的公共 ip 的 terraform 代码,这是我的代码

# 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/"
    }}

这里使用的是 NIC id ,默认情况下会提供公共 ip,有人可以帮我吗?

4

2 回答 2

4

您将为此使用数据模块:

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

这将为您提供 NIC 对象,该对象将具有ip_configuration块,(反过来)将具有public_ip_address_id参数,您将使用它来获取公共 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 解析为资源组\名称,但这可以通过拆分 + 数组索引轻松完成

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

于 2019-01-02T07:19:10.203 回答
0

我试过了,无法检索公共 IP。(很可能是飞行员错误。)

在我的情况下,我需要在后面的步骤中检索一个安装 chef 的地址,所以 IP 或 FQDN 可以工作。这是我如何度过难关的:

创建我的公共 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。一旦你有了它,你就可以使用/检索 fqdn。

output "AzurePage" {
value = "${azurerm_public_ip.CSpublicip.fqdn}"
于 2019-08-02T13:01:33.313 回答