Terraform – building a dynamic ansible inventory using templatefile

Terraform is a tool to create virtual machines. It is usually not used to configure and manage them.

Ansible is a tool to configure and manage virtual machines. To do this, Ansible will need an inventory file.

Since Terraform was used to create the instances, it has all the information needed to produce an Ansible inventory file. And Terraform can output information. Getting it to write an Ansible inventory should be simple.

Contents of the template file ansible_inventory.tmpl which Terraform uses to generate an Ansible inventory.

%{ if is_windows_image == true }[windows]%{ else }[linux]%{ endif }
%{ for index, hostname in hostnames ~}
${hostname} ansible_host=${ansible_hosts[index]}
%{ endfor ~}

In your Terraform’s output.tf you usually define a local_file resource, which uses the hostnames and the IP addresses of your created VMs to generate a dynamic inventory file for Ansible.

resource "local_file" "AnsibleInventory" {
 content = templatefile("ansible_inventory.tmpl",
  hostnames         = azurerm_virtual_machine.vm.*.name,
  ansible_hosts     = azurerm_network_interface.vm.*.private_ip_address,
  is_windows_image  = true
 filename = "dynamic_inventory"

Example of a resulting Ansible dynamic_inventory file

rdsh01 ansible_host=
rdsh02 ansible_host=