Using Ansible and Terraform Together
2020-02-01
This should be a short one. So Ansible has dynamic inventories however I’ve found it a bit slow with VMware if you have a lot of infrastructure to parse through (a lot being around 3,000 VMs in your vCenter and slow being around 15 minutes). I also couldn’t figure out a way to use tags to limit what you’re searching on. This admittedly could have changed recently but since I’ve been using this method I haven’t tried too hard to find out. However, if you’re running in a pipeline, you can just have Terraform generate a static inventory for Ansible to use during the pipeline.
To do this you just need to use the local_filelocal_file provider with the template_filetemplate_file data source. So for a simple example we could just use our output variables from our module in our template.
main.tf
module "testing" { #misc module variables}data "template_file" "inventory" { template = file("./inventory.tpl") vars = { servers = "${join("\n", formatlist("%s ansible_host=%s", module.testing.server_names, module.testing.server_ips))}" }}resource "local_file" "ansible_inventory" { content = "${data.template_file.inventory.rendered} filename = "./inventory"}
module "testing" { #misc module variables}data "template_file" "inventory" { template = file("./inventory.tpl") vars = { servers = "${join("\n", formatlist("%s ansible_host=%s", module.testing.server_names, module.testing.server_ips))}" }}resource "local_file" "ansible_inventory" { content = "${data.template_file.inventory.rendered} filename = "./inventory"}
template.tpl
[servers]${servers}
[servers]${servers}
Obviously tailor the module name and output variable names to the correct ones. If you output an FQDN then you don’t need the ip addres and ansible_hostansible_host in the inventory. Rinse and repeat for however many groups you want.