Search code examples
azureansibleterraformterraform-provider-azure

How to pass Azure VM public ip address (created by Terraform) to Ansible?


I have a main.tf file which created my Azure VM and a Virtualbox Ubuntu VM for configuring the Azure VM.

data "azurerm_public_ip" "vm-publicip" {
  name                = azurerm_public_ip.public.name
  resource_group_name = azurerm_resource_group.main.name
}

output "vm-publicip" {
  value = data.azurerm_public_ip.vm-publicip.ip_address
}

Can you advise how to automatically pass the public IP address of the Azure VM to Ansible on the Virtualbox VM so that it could automatically configure the Azure VM?

I suppose a viable solution might be running Terraform also on the Ubuntu VM but is there any option that might be used?


Solution

  • Based on the code from the question, I would suggest using the terraform_data resource. You would then do something like the following:

    data "azurerm_public_ip" "vm-publicip" {
      name                = azurerm_public_ip.public.name
      resource_group_name = azurerm_resource_group.main.name
    }
    
    resource "terraform_data" "ansible" {
      provisioner "local-exec" {
        command = "echo ${data.azurerm_public_ip.vm-publicip.ip_address} >> /etc/ansible/hosts"
      }
    }
    
    output "vm-publicip" {
      value = data.azurerm_public_ip.vm-publicip.ip_address
    }