AWS Terraform to Ansible Inventory

Problem:

I would like to provision servers to AWS with Terraform, but an Ansible Infrastructure Provider is not available.

I want to avoid performing manual work (brr) and automate all the things. If I borrow the inventory from Terraform, then I can use it in Ansible directly!

Solution:

Ansible is working towards having inventories in YAML. Terraform has the function yamlencode.

For the example below, I use my own EC2 module. There is a publicly available EC2 module.

These two output fields are returned by my module:

  • private_ip
  • ssh_username

With this data structure in place, this example is possible:

ansible.tf:

locals {
    ansible_inventory = yamlencode(
        {
            all: {
                hosts: {
                    for ec2 in keys(module.ec2): my_index => {
                        ansible_host: module.ec2[my_index].private_ip,
                        ansible_user: module.ec2[my_index].ssh_username
                    }
                }
            }
        }
    )
}

resource "local_file" "ansible_inventory" {
    filename = "inventory"
    content = local.ansible_inventory
}

output "ansible_inventory" {
    value = local.ansible_inventory
}

It will result in the inventory file below:

inventory:

all:
  hosts:
    my_ec2_host:
      ansible_host: 172.16.12.12
      ansible_user: ubuntu

This inventory can be validated this way:

ansible-inventory --list -i inventory all

The final step is to verify connectivity using Ansible:

ansible -i inventory -m ping all

Happy provisioning!