TExcelTAD
Home › Configuration Management: Ansible › Create with Terraform, Configure with Ansible

Create with Terraform, Configure with Ansible

Terraform and OpenTofu are best at creating infrastructure: networks, VMs, load balancers, DNS, with a plan you review and state that tracks every object. Ansible is best at configuring what runs inside a machine: users, packages, files, services. The usual split:

Step Tool Output
1. create VPC, subnets, security groups, VMs Terraform IP addresses, instance ids, tags
2. hand the hosts over Terraform outputs, tags, or a generated inventory an Ansible inventory
3. configure the OS and the app Ansible a server that matches the roles

Each tool can do a bit of the other's job (Terraform remote-exec provisioners, Ansible cloud modules such as amazon.aws.ec2_instance), but both work worse that way: Terraform provisioners run once at creation and are invisible to later plans, and Ansible has no plan or state for cloud resources.

The hand-over: three ways

Way How Good for
dynamic inventory from tags Terraform tags each VM (Role = "web"); the amazon.aws.aws_ec2 plugin groups them (Dynamic Inventories) cloud fleets; nothing to keep in sync
generated inventory file Terraform writes inventory.yml with a local_file resource from its outputs small setups, labs, on-prem
inventory from state the cloud.terraform collection reads the state (cloud.terraform.terraform_state inventory plugin) when VMs have no useful tags

A generated inventory, end to end

This session does all three steps offline. Terraform's "VMs" are terraform_data resources standing in for aws_instance (they produce addresses the same way), the inventory is a real file written by the local provider, and Ansible then configures the hosts, which point at the sandbox itself:

bash · try it yourself
mkdir -p infra config && cd infra
cat > main.tf <<'HCL'
variable "web_count" {
  type    = number
  default = 2
}

# stands in for aws_instance.web (count = var.web_count)
resource "terraform_data" "web" {
  count = var.web_count
  input = {
    name       = "web-${count.index + 1}"
    private_ip = "10.0.1.${10 + count.index}"
  }
}

resource "terraform_data" "db" {
  input = { name = "db-1", private_ip = "10.0.2.10" }
}

resource "local_file" "inventory" {
  filename        = "${path.module}/../config/inventory.yml"
  file_permission = "0644"
  content = yamlencode({
    all = {
      vars = { ansible_connection = "local" }   # real VMs: ansible_user, ProxyJump, ...
      children = {
        web = { hosts = { for w in terraform_data.web : w.output.name => { private_ip = w.output.private_ip } } }
        db  = { hosts = { (terraform_data.db.output.name) = { private_ip = terraform_data.db.output.private_ip } } }
      }
    }
  })
}
HCL
tofu init >/dev/null && tofu apply -auto-approve | tail -1
cd ../config
ansible-inventory -i inventory.yml --graph
cat > ansible.cfg <<'INI'
[defaults]
inventory = inventory.yml
interpreter_python = auto_silent
forks = 1
INI
cat > site.yml <<'YML'
- name: Configure the web tier
  hosts: web
  gather_facts: false
  tasks:
    - name: App config pointing at the database
      ansible.builtin.copy:
        dest: "/home/learner/{{ inventory_hostname }}.env"
        content: |
          LISTEN={{ private_ip }}:8080
          DB_HOST={{ hostvars[groups['db'][0]].private_ip }}
        mode: "0644"
YML
ansible-playbook site.yml | grep -E '^(changed|ok):|^web'
cat /home/learner/web-2.env
Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
@all:
  |--@ungrouped:
  |--@db:
  |  |--db-1
  |--@web:
  |  |--web-1
  |  |--web-2
changed: [web-1]
changed: [web-2]
web-1                      : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
web-2                      : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
LISTEN=10.0.1.11:8080
DB_HOST=10.0.2.10

Scale out by changing one number: tofu apply -var web_count=3 adds a host to the plan, rewrites the inventory, and the next Ansible run configures web-3, while web-1 and web-2 report ok.

On AWS

The real versions of the two steps (sample code; it needs an AWS account):

hcl
resource "aws_instance" "web" {
  count                  = 2
  ami                    = data.aws_ami.ubuntu.id
  instance_type          = "t3.small"
  subnet_id              = aws_subnet.private[count.index].id
  vpc_security_group_ids = [aws_security_group.web.id]
  key_name               = "ada"
  tags = { Name = "linkly-web-${count.index + 1}", Role = "web", Project = "linkly" }
}
yaml
# inventory/aws_ec2.yml
plugin: amazon.aws.aws_ec2
regions: [eu-west-1]
filters: {"tag:Project": linkly, instance-state-name: running}
keyed_groups: [{key: tags.Role, prefix: "", separator: ""}]   # group "web"
hostnames: [tag:Name]
compose: {ansible_host: private_ip_address}

Wiring it into a pipeline

yaml
# a GitLab CI sketch: plan, apply, then configure
stages: [plan, apply, configure]
plan:      {stage: plan,      script: [tofu init, tofu plan -out=tfplan], artifacts: {paths: [tfplan]}}
apply:     {stage: apply,     script: [tofu init, tofu apply tfplan], when: manual}
configure:
  stage: configure
  script:
    - ansible-galaxy collection install -r requirements.yml
    - ansible-playbook -i inventory/aws_ec2.yml site.yml --diff

First boot vs every run. Give new VMs only what they need to be reachable through cloud-init user_data (an admin user and SSH key), and let Ansible do everything else, so a server built today and one built a year ago run the same roles. For immutable setups, run the same roles inside Packer to bake an image, and let Terraform launch that image: Ansible then configures images, not live servers.

Test yourself

In the usual split, which tool creates the VMs and which installs nginx on them?

  1. Ansible creates, Terraform installs
  2. Terraform creates, Ansible installs
  3. Both create
  4. Terraform does both with provisioners

Why are dynamic inventories from cloud tags popular for the hand-over?

  1. They are faster than files
  2. Nothing has to be kept in sync: new tagged VMs appear in the right groups automatically
  3. They don't need credentials
  4. Terraform requires them

Why avoid Terraform's remote-exec provisioner for server configuration?

  1. It is not supported
  2. It runs once at creation and later changes are invisible to plans
  3. It needs Ansible
  4. It costs money