# Share variables between Terraform and Ansible

# Why?

You are building a stack which uses Terraform to create the infrastructure then Ansible to configure services on instances like Wordpress website. You will probably need to know the address of the Amazon RDS database, or the address of the Amazon Elasticache.

This information could be pre-defined for example using Amazon Route53, service discovery like Consul or by defining shared variables between Terraform and Ansible.

# How?

Currently we provide Terraform information to Ansible based on Terraform outputs : https://www.terraform.io/language/values/outputs (opens new window)

As Terraform and Ansible are run by your pipeline, it’s easy to provide the Terraform output to Ansible as variables.

# Example in the Magento stack

  1. To do that you first have to define a Terraform output:

stack-magento/terraform/outputs.tf (opens new window)

output "rds_address" {
  value = "${module.magento.rds_address}"
}
1
2
3
  1. Then in the Ansible job of your pipeline, ensure you get the output of Terraform job.

stack-magento/pipeline/pipeline.yml (opens new window)

And add this as input for the merge-stack-and-config task. By providing a “terraform” directory as input, the merge task will provide all Terraform outputs to Ansible as global variables in group_vars/all

stack-magento/pipeline/pipeline.yml (opens new window)

- task: merge-stack-and-config
   config:
     <<: *merge-stack-and-config
     inputs:
     - name: catalog-config-ansible
       path: "config"
     - name: stack-magento-ansible
       path: "stack"
     - name: terraform-magento-((env))
       path: "terraform"
   params:
     CONFIG_PATH: ansible
     STACK_PATH: ansible
1
2
3
4
5
6
7
8
9
10
11
12
13
  1. Just use those new variables in Ansible

stack-magento/ansible/environments/default_front.yml (opens new window)

magento_db_host: "{{ rds_address | default('localhost') }}"
1