To generate the Ansible inventory with Terraform, perform the following steps:
- Inside the folder containing the Terraform configuration, we create a new file called template-inventory.tpl with the following content:
[vm-web]
%{ for host, dns in vm_dnshost ~}
${host} ansible_host=${dns}
%{ endfor ~}
- Then, in the main.tf file of the Terraform configuration that creates a VM, we add the following code to generate the inventory file:
resource "local_file" "inventory" {
filename = "inventory"
content = templatefile("template-inventory.tpl",
{
vm_dnshost = zipmap(var.vmhosts,module.linuxservers.network_interface_private_ip)
})
}
- Finally, to create the VMs and generate the inventory file, we run the basic Terraform init, plan, and apply workflow commands.