Run Ansible Playbooks with Terraform

Terraform from Hashicorp as the slogan is to write,plan and create structure as code.
Terraform can describe an execution plan generated from configurations of what it will do to reach the desired state, and then executes it to construct the infrastructure. It can identify what are the configuration changes, and create incremental execution plans which can be applied.

Terraform has several provisioners but it would be nice to have Ansible.

Presented here is Terraform Ansible provisioner which is a plugin provisioner that will able to run playbooks to setup the machine. Currently only supports Ubuntu for it’s bootstrap command but can be modified further to support installing Ansible for distro.

As of this writing, Terraform is on version 0.7.13 and the problem is that the Ansible provisioner, which is written in Golang, needs to be compiled to work for this Terraform version.

Here are the steps using Ubuntu Trusty using Vagrant box:

$ mkdir terraform-trusty64
$ cd terraform-trusty64/
$ vagrant init ubuntu/trusty64
$ vagrant up
$ vagrant ssh

Run this script in order to setup Golang and the rest of needed work.

$ curl -o setup.sh https://gist.githubusercontent.com/cocoy/5e22a249cbb78eeeee126473b728eaaa/raw/6678f478700aa7a07942ec651b302fdc65689161/gistfile1.txt 
$ chmod +x setup.sh
$ ./setup.sh

This will complete the compilation and setup terraform with the ansible provisioner.

$ cd ~/work/src/terraform-provisioner-ansible/example
$ curl -o example.tf https://gist.github.com/cocoy/2a0c41597c47c64fd4f9b3c73b49b86f

The example.tf was downloaded. But should be editted for access and secret keys, and other AWS related inputs.

Then finally:

$ terraform plan
$ terraform apply 

In summary, the beauty of this is we can re-use our existing playbooks/roles together with AWS and other service providers. Hopefully this provisioner will soon be added as a core part to Terraform.

2 thoughts on “Run Ansible Playbooks with Terraform

Leave a Reply

Your email address will not be published. Required fields are marked *