In the previous lesson you created Aurora Store's staging environment on AWS with Ansible alone: it works, but staging-aws.yml chains a dozen tasks together through registered identifiers, and the destruction playbook has to repeat the same resources in reverse order, by hand. There's a tool designed specifically for that problem: Terraform (and its open source fork, OpenTofu), which keeps a state of everything it has created, works out the order of dependencies and knows how to destroy what it built. In this lesson you'll understand how Terraform and Ansible split the work, you'll learn the patterns for integrating them (Terraform creates and Ansible configures; Ansible runs Terraform; and the discouraged local-exec provisioner), and you'll rebuild Aurora's staging environment with Terraform/OpenTofu for provisioning and Ansible for configuration, with the state and its locks under control.

Contents

  1. Two tools, two specialties
  2. Terraform and OpenTofu: the essentials
  3. Integration patterns
  4. Aurora's staging in Terraform
  5. Pattern A: Terraform creates and Ansible reads its outputs
  6. Pattern B: Ansible runs Terraform (the one Aurora adopts)
  7. The state: local, remote and locked
  8. Why not to use the local-exec provisioner
  9. Migrating the staging environment from Lesson 8.4
  10. When to choose each approach

  1. Two tools, two specialties

Both tools are "infrastructure as code" and, in theory, each can do the other's job. In practice, each one is much better on its own turf:

Aspect Terraform / OpenTofu Ansible
Specialty Provisioning: creating resources through APIs (networks, machines, managed databases, DNS…) Configuring: what happens inside the servers (packages, files, services, deployments) and orchestrating processes
Model Purely declarative: you describe the final state of a set of resources Declarative per task, with tasks run in order
State Keeps a state file with everything it manages Stateless: queries reality on every run
Dependencies Works them out on its own (resource graph) You express them through task order and register
Preview plan: an exact list of what it will create, change or destroy --check --diff: a good approximation, not always exact
Destruction destroy removes everything in the state, in the right order You have to write a destruction playbook
Resources no longer in the code Destroys them on the next apply Ignores them (you have to declare them with state: absent)
Inside the server Very limited (and discouraged) Its natural territory
Processes with steps and conditions Not its job Its natural territory (serial, rescue, delegation, approvals in AWX)

The usual conclusion in the industry: Terraform builds the house, Ansible furnishes it and looks after it. The meeting point is the information Ansible needs about what Terraform created: the machines' IPs, names and roles.

  1. Terraform and OpenTofu: the essentials

2.1. Terraform and OpenTofu

Terraform is made by HashiCorp. In 2023 it changed its license to a non-open-source one (BSL), and the community created OpenTofu, an open source fork (MPL 2.0) maintained under the Linux Foundation. Both use the same language (HCL), the same providers and the same commands (terraform or tofu). Everything you'll see works with both; Aurora uses OpenTofu in the lab. Install it following the official documentation at opentofu.org and check:

tofu version
command -v tofu          # e.g. /usr/bin/tofu (you'll need the path in section 6)

2.2. Concepts

Concept What it is Rough equivalent in Ansible
Provider A plugin that talks to an API (hashicorp/aws) A collection (amazon.aws)
Resource A managed object (aws_instance) A task with state: present
Data source A read-only query (aws_ami) An *_info module
Variable / output The project's inputs and outputs Variables / register
State A JSON file mapping code ↔ real resources — (doesn't exist)
Plan / apply / destroy Calculate / apply / remove --check / run / destruction playbook

The workflow:

tofu init       # downloads the providers and prepares the state
tofu plan       # shows what's going to change
tofu apply      # applies (asks for confirmation)
tofu output     # shows the outputs
tofu destroy    # removes everything in the state

  1. Integration patterns

flowchart LR
    subgraph A["A. Terraform creates → Ansible configures"]
        A1[tofu apply] --> A2[outputs / state] --> A3[Ansible inventory] --> A4[ansible-playbook]
    end
    subgraph B["B. Ansible runs Terraform"]
        B1[ansible-playbook] --> B2[terraform module] --> B3[outputs] --> B4[add_host] --> B5[configuration plays]
    end
    subgraph C["C. Terraform calls Ansible (discouraged)"]
        C1[tofu apply] --> C2[local-exec provisioner] --> C3[ansible-playbook]
    end
Pattern How the information is passed Advantages Drawbacks
A. Terraform creates → Ansible configures tofu output -json turned into an inventory (template), or an inventory plugin that reads the state (cloud.terraform.terraform_provider, cloud.terraform.terraform_state) or the cloud (amazon.aws.aws_ec2, Lesson 10.2) Decoupled tools; each team uses its own; fits two-stage pipelines Two commands that have to be coordinated
B. Ansible runs Terraform The community.general.terraform module (or cloud.terraform.terraform) returns the outputs; add_host turns them into hosts A single entry point (one playbook, one AWX template); approvals and logging in AWX The control node (or the EE) needs the Terraform binary and access to the state
C. Terraform calls Ansible A local-exec provisioner that runs ansible-playbook when each resource is created Apparent simplicity Discouraged: see section 8

  1. Aurora's staging in Terraform

Create the terraform/staging/ directory in aurora-infra with four files. It's the same design as in Lesson 8.4 (VPC 10.40.0.0/16, public subnet, internet gateway, routes, two security groups, two web servers and one database), but expressed in HCL.

terraform/staging/versions.tf:

terraform {
  required_version = ">= 1.8"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

provider "aws" {
  region = var.region

  # Tags applied to ALL the project's resources.
  default_tags {
    tags = {
      Project     = "aurora"
      Environment = "staging"
      ManagedBy   = "terraform"
    }
  }
}

terraform/staging/variables.tf:

variable "region" {
  type    = string
  default = "eu-south-2"
}

variable "az" {
  type    = string
  default = "eu-south-2a"
}

variable "vpc_cidr" {
  type    = string
  default = "10.40.0.0/16"
}

variable "subnet_cidr" {
  type    = string
  default = "10.40.1.0/24"
}

variable "admin_cidr" {
  description = "The only network allowed to use SSH (your public IP /32)"
  type        = string
}

variable "instance_type" {
  type    = string
  default = "t3.micro"
}

variable "web_count" {
  type    = number
  default = 2
}

variable "db_count" {
  type    = number
  default = 1
}

variable "ssh_public_key_file" {
  type = string
}

variable "ami_name" {
  type    = string
  default = "ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*"
}

terraform/staging/main.tf:

locals {
  name = "aurora-staging"
}

# Official Ubuntu 24.04 from Canonical, the most recent one.
data "aws_ami" "ubuntu" {
  most_recent = true
  owners      = ["099720109477"]

  filter {
    name   = "name"
    values = [var.ami_name]
  }
  filter {
    name   = "architecture"
    values = ["x86_64"]
  }
}

resource "aws_vpc" "this" {
  cidr_block           = var.vpc_cidr
  enable_dns_hostnames = true
  tags                 = { Name = local.name }
}

resource "aws_subnet" "public" {
  vpc_id                  = aws_vpc.this.id
  cidr_block              = var.subnet_cidr
  availability_zone       = var.az
  map_public_ip_on_launch = true
  tags                    = { Name = "${local.name}-public" }
}

resource "aws_internet_gateway" "this" {
  vpc_id = aws_vpc.this.id
  tags   = { Name = "${local.name}-igw" }
}

resource "aws_route_table" "public" {
  vpc_id = aws_vpc.this.id
  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.this.id
  }
  tags = { Name = "${local.name}-public" }
}

resource "aws_route_table_association" "public" {
  subnet_id      = aws_subnet.public.id
  route_table_id = aws_route_table.public.id
}

resource "aws_security_group" "web" {
  name        = "${local.name}-web"
  description = "Aurora Store web servers (staging)"
  vpc_id      = aws_vpc.this.id

  ingress {
    description = "SSH from the admin IP"
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = [var.admin_cidr]
  }
  ingress {
    description = "Public HTTP"
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_security_group" "db" {
  name        = "${local.name}-db"
  description = "Aurora Store database (staging)"
  vpc_id      = aws_vpc.this.id

  ingress {
    description = "SSH from the admin IP"
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = [var.admin_cidr]
  }
  ingress {
    description     = "PostgreSQL from the web servers"
    from_port       = 5432
    to_port         = 5432
    protocol        = "tcp"
    security_groups = [aws_security_group.web.id]
  }
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_key_pair" "staging" {
  key_name   = local.name
  public_key = file(var.ssh_public_key_file)
}

resource "aws_instance" "web" {
  count                  = var.web_count
  ami                    = data.aws_ami.ubuntu.id
  instance_type          = var.instance_type
  subnet_id              = aws_subnet.public.id
  vpc_security_group_ids = [aws_security_group.web.id]
  key_name               = aws_key_pair.staging.key_name

  root_block_device {
    volume_size = 10
    volume_type = "gp3"
  }

  tags = { Name = "${local.name}-web-${count.index + 1}", Role = "web" }

  # A new Canonical AMI must not replace the existing instances.
  lifecycle {
    ignore_changes = [ami]
  }
}

resource "aws_instance" "db" {
  count                  = var.db_count
  ami                    = data.aws_ami.ubuntu.id
  instance_type          = var.instance_type
  subnet_id              = aws_subnet.public.id
  vpc_security_group_ids = [aws_security_group.db.id]
  key_name               = aws_key_pair.staging.key_name

  root_block_device {
    volume_size = 10
    volume_type = "gp3"
  }

  tags = { Name = "${local.name}-db-${count.index + 1}", Role = "db" }

  lifecycle {
    ignore_changes = [ami]
  }
}

terraform/staging/outputs.tf:

output "servers" {
  description = "The environment's servers, in the format the Ansible playbook expects"
  value = [
    for i in concat(aws_instance.web, aws_instance.db) : {
      name       = i.tags["Name"]
      role       = i.tags["Role"]
      public_ip  = i.public_ip
      private_ip = i.private_ip
    }
  ]
}

Compare with Lesson 8.4:

  • There's no register anywhere: aws_subnet.public.id is a reference, and from the set of references Terraform deduces the order of creation (and the reverse for destruction).
  • default_tags on the provider tags everything automatically, without repeating tags on every resource (and without the risk of divergence from Exercise 3 in Lesson 8.4).
  • count creates N instances of a resource: it's the equivalent of exact_count. When the number goes down, Terraform destroys the ones with the highest index.
  • lifecycle { ignore_changes = [ami] } reproduces the decision from Lesson 8.4: the image only affects new instances.
  • The servers output is the contract between Terraform and Ansible: a list with each machine's name, role and IPs. Ansible doesn't need to know anything else about the state.

Terraform providers read the same credentials as amazon.aws (AWS_PROFILE, environment variables…). No credentials in the .tf files.

Add to .gitignore:

# Terraform / OpenTofu (Lesson 8.5)
.terraform/
*.tfstate
*.tfstate.*
*.tfplan
terraform.tfvars

The .terraform.lock.hcl file that tofu init will create is versioned: it pins the exact provider versions, just like the exact versions in collections/requirements.yml.

  1. Pattern A: Terraform creates and Ansible reads its outputs

First, by hand, to understand each piece:

export AWS_PROFILE=aurora-staging
cd terraform/staging
tofu init
tofu plan -var admin_cidr=203.0.113.25/32 -var ssh_public_key_file=$HOME/.ssh/aurora_staging_ed25519.pub

The plan ends with a line like Plan: 11 to add, 0 to change, 0 to destroy. (VPC, subnet, internet gateway, route table, its association with the subnet, 2 security groups, key pair and 3 instances, with their disks included). If you applied it (tofu apply with the same variables), you'd get the outputs:

tofu output -json servers
[
  {"name": "aurora-staging-web-1", "private_ip": "10.40.1.11", "public_ip": "198.51.100.21", "role": "web"},
  {"name": "aurora-staging-web-2", "private_ip": "10.40.1.12", "public_ip": "198.51.100.37", "role": "web"},
  {"name": "aurora-staging-db-1", "private_ip": "10.40.1.13", "public_ip": "198.51.100.52", "role": "db"}
]

In pattern A, that JSON is turned into an inventory. The simplest way, with a Jinja2 template in a localhost play (an illustrative example, not adopted):

- name: Generate the staging inventory from the Terraform outputs
  hosts: localhost
  connection: local
  gather_facts: false
  vars:
    servers: "{{ lookup('ansible.builtin.pipe', 'tofu -chdir=terraform/staging output -json servers') | from_json }}"
  tasks:
    - name: Write the inventory
      ansible.builtin.copy:
        dest: cloud/staging-hosts.yml
        mode: "0644"
        content: |
          # Generated from the Terraform outputs. Do not edit.
          staging_aws:
            children:
          {% for role in servers | map(attribute='role') | unique %}
              staging_{{ role }}:
                hosts:
          {% for s in servers | selectattr('role', 'equalto', role) %}
                  {{ s.name }}:
                    ansible_host: {{ s.public_ip }}
          {% endfor %}
          {% endfor %}

Configuration would then be done by combining inventories (Aurora's, for its group_vars/all, and the generated one): ansible-playbook -i inventory -i cloud/staging-hosts.yml ....

There are alternatives without an intermediate file:

  • The cloud.terraform collection includes inventory plugins: cloud.terraform.terraform_state builds hosts from the resources (for example, aws_instance) in the state file, and cloud.terraform.terraform_provider reads ansible_host and ansible_group resources that you declare in Terraform with the ansible/ansible provider.
  • The cloud's dynamic inventory (amazon.aws.aws_ec2), which doesn't depend on Terraform at all: it reads the instances and their tags from the API (Lesson 10.2).

Pattern A is very common when the platform team uses Terraform in its own pipeline and the systems team uses Ansible in theirs.

  1. Pattern B: Ansible runs Terraform (the one Aurora adopts)

6.1. Why

Aurora has AWX with permissions, approvals and history, and wants a single entry point for its staging environment: a playbook that provisions and configures. That's why it adopts pattern B: Ansible runs Terraform with the community.general.terraform module (the community.general collection is already an Aurora dependency). The module runs init, plan and apply (or destroy) and returns the outputs.

The cloud.terraform collection (maintained by Red Hat and certified in Ansible Automation Platform) offers the cloud.terraform.terraform module, derived from the community.general one, as well as the inventory plugins from section 5. If Aurora ever used AAP, it would be the natural choice; usage is practically the same.

6.2. Variables

cloud/aws-staging.yml now looks like this (the variables that Terraform now manages, such as the key pair name or the AMI owner, disappear):

---
# Aurora Store staging environment on AWS, provisioned with OpenTofu/Terraform (Lesson 8.5).
# Example values: adjust the region, the zone and YOUR public IP before running.
aurora_staging_name: aurora-staging
aurora_staging_region: eu-south-2
aurora_staging_az: eu-south-2a
aurora_staging_vpc_cidr: 10.40.0.0/16
aurora_staging_subnet_cidr: 10.40.1.0/24
aurora_staging_admin_cidr: 203.0.113.25/32
aurora_staging_instance_type: t3.micro
aurora_staging_web_count: 2
aurora_staging_db_count: 1
aurora_staging_ssh_key: "{{ lookup('ansible.builtin.env', 'HOME') }}/.ssh/aurora_staging_ed25519"

# Terraform project and binary (absolute path: "command -v tofu" or "command -v terraform").
aurora_staging_tf_project: terraform/staging
aurora_staging_tf_binary: /usr/bin/tofu

6.3. The staging-terraform.yml playbook

---
# Provisions (OpenTofu/Terraform) and configures (Ansible) the Aurora Store staging environment.
# Create or update: ansible-playbook staging-terraform.yml
# Destroy:          ansible-playbook staging-terraform.yml -e aurora_staging_state=absent -e confirm=aurora-staging
# Creates billable resources on AWS! Requirements: tofu (or terraform) and credentials (AWS_PROFILE).
- name: Provision the Aurora Store staging environment with Terraform
  hosts: localhost
  connection: local
  gather_facts: false
  vars_files:
    - cloud/aws-staging.yml
  vars:
    aurora_staging_state: present

  tasks:
    - name: Require confirmation to destroy
      ansible.builtin.assert:
        that: confirm | default('') == aurora_staging_name
        fail_msg: "To destroy the environment, add -e confirm={{ aurora_staging_name }}"
      when: aurora_staging_state == 'absent'

    - name: Apply the environment's Terraform project
      community.general.terraform:
        project_path: "{{ aurora_staging_tf_project }}"
        binary_path: "{{ aurora_staging_tf_binary }}"
        state: "{{ aurora_staging_state }}"
        force_init: true
        variables:
          region: "{{ aurora_staging_region }}"
          az: "{{ aurora_staging_az }}"
          vpc_cidr: "{{ aurora_staging_vpc_cidr }}"
          subnet_cidr: "{{ aurora_staging_subnet_cidr }}"
          admin_cidr: "{{ aurora_staging_admin_cidr }}"
          instance_type: "{{ aurora_staging_instance_type }}"
          web_count: "{{ aurora_staging_web_count }}"
          db_count: "{{ aurora_staging_db_count }}"
          ssh_public_key_file: "{{ aurora_staging_ssh_key }}.pub"
      register: aurora_staging_tf

    - name: Add the servers to this run's inventory
      ansible.builtin.add_host:
        name: "{{ item.name }}"
        groups:
          - staging_aws
          - "staging_{{ item.role }}"
        ansible_host: "{{ item.public_ip }}"
        ansible_user: ubuntu
        ansible_ssh_private_key_file: "{{ aurora_staging_ssh_key }}"
        ansible_ssh_common_args: -o StrictHostKeyChecking=accept-new
        aurora_env: staging
        aurora_staging_private_ip: "{{ item.private_ip }}"
      loop: "{{ aurora_staging_tf.outputs.servers.value | default([]) }}"
      loop_control:
        label: "{{ item.name }} {{ item.public_ip }}"
      when: aurora_staging_state == 'present'
      changed_when: false

- name: Configure the staging environment servers
  ansible.builtin.import_playbook: staging-configure.yml

And staging-configure.yml, with the second play from Lesson 8.4 unchanged:

---
# Base configuration of the staging servers (staging_aws group).
# Imported from staging-terraform.yml, which adds the hosts with add_host.
- name: Configure the staging environment servers
  hosts: staging_aws
  gather_facts: false
  become: true

  pre_tasks:
    - name: Wait for the servers to accept SSH connections
      ansible.builtin.wait_for_connection:
        timeout: 300

    - name: Wait for cloud-init to finish booting
      ansible.builtin.command:
        cmd: cloud-init status --wait
      changed_when: false

    - name: Gather the minimal facts
      ansible.builtin.setup:
        gather_subset: [min]

  roles:
    - common

Key points:

  • project_path: the directory with the .tf files. binary_path: OpenTofu instead of Terraform (an absolute path, as the module requires).
  • force_init: true: runs init if the project isn't initialized (downloading providers, preparing the state).
  • variables: passed to Terraform as -var. By default it only accepts strings and numbers (for lists or maps there's complex_vars: true). A single source of truth: cloud/aws-staging.yml; the default values in variables.tf are only for whoever uses tofu by hand.
  • state: present = apply; absent = destroy; there's also planned to generate a plan without applying it.
  • The result includes outputs, and each output has value, type and sensitive. aurora_staging_tf.outputs.servers.value is exactly the list from section 5.
  • Check mode: with --check, the module runs a plan and reports whether there would be changes, without applying them (with --diff, it shows the details).
  • Destroying is the same playbook with aurora_staging_state=absent and the confirmation: Terraform knows what to destroy and in what order because it's in its state. Since there are no hosts to add, the imported play finds no hosts and is skipped ("skipping: no hosts matched").
  • Notice the contrast with Lesson 8.4: the playbook goes from a dozen tasks plus a second destruction playbook to a single provisioning task. The complexity doesn't disappear: it moves into the .tf files, where Terraform handles it better.

6.4. Running it

export AWS_PROFILE=aurora-staging
ansible-playbook staging-terraform.yml --check      # plan: 11 resources to create
ansible-playbook staging-terraform.yml               # provisions and configures
ansible-playbook staging-terraform.yml               # idempotency: changed=0 in both plays
ansible-playbook staging-terraform.yml -e aurora_staging_state=absent -e confirm=aurora-staging

After the second run, Terraform reports that there are no changes (No changes.) and the module returns changed=false; common doesn't change anything either. At the end, check in the AWS console that nothing of the environment is left.

  1. The state: local, remote and locked

7.1. What it is and why it matters

After the first apply, terraform.tfstate appears in terraform/staging/: a JSON file with each managed resource and its real ID (vpc-0a1b2c3d4e5f60718…). It's what lets Terraform know that the VPC "already exists" without searching for it by tags. Three consequences:

  • If the state is lost, Terraform thinks nothing exists and will try to create everything again (with duplicates or errors), and destroy will no longer know what to delete.
  • It contains sensitive data (addresses, sometimes resource passwords): that's why it's in .gitignore. It's never versioned in Git.
  • If two people apply at the same time against the same state, they can corrupt it.

7.2. Remote state with locking

As soon as more than one person (or AWX, or CI) manages the environment, the state must live in a shared, encrypted remote backend with locking. On AWS, the usual choice is an S3 bucket (with versioning, to recover earlier states). It would be declared in versions.tf:

terraform {
  backend "s3" {
    bucket       = "aurora-tfstate-example"
    key          = "staging/terraform.tfstate"
    region       = "eu-south-2"
    encrypt      = true
    use_lockfile = true   # native S3 locking (Terraform and OpenTofu 1.10+); a DynamoDB table was used before
  }
}
Aspect Local state (Aurora lab) Remote state (production)
Where terraform/staging/terraform.tfstate on your computer S3 bucket, Azure Storage, GCS, HCP Terraform, GitLab…
Shared No Yes
Locking Only on your computer Yes (use_lockfile or the backend's equivalent)
Backups Your own Bucket versioning
From AWX or CI Impossible: the EE is ephemeral and the state would be lost when the job ends Yes

The last point is decisive for Aurora: launching staging-terraform.yml from AWX would require a remote backend, the tofu binary inside aurora-ee (with additional_build_steps in the EE definition) and the AWS credential from Lesson 8.4. With the module, the backend_config or backend_config_files parameters let you pass the backend configuration at init time. OpenTofu also offers client-side state encryption, a notable difference from Terraform.

Aurora keeps local state as long as staging is a personal test environment, and notes the remote backend as a requirement before sharing or automating it.

  1. Why not to use the local-exec provisioner

Terraform lets you run commands when a resource is created:

resource "aws_instance" "web" {
  # ...
  provisioner "local-exec" {
    command = "ansible-playbook -i '${self.public_ip},' webservers.yml"
  }
}

It looks convenient, but Terraform's own documentation presents provisioners as a last resort:

Problem Why
It only runs when the resource is created If you change the configuration, Ansible doesn't run again; if it fails halfway, the resource is marked as faulty (tainted) and will be recreated
One run per resource Each instance is configured separately: no serial, no groups, no shared variables
No visibility in the plan plan says nothing about what Ansible will do
Mixes responsibilities Provisioning depends on Ansible, its collections and its secrets being available at that moment
Doesn't reach AWX Deployments are left out of the history, permissions and approvals

To prepare the bare minimum at first boot (creating a user, installing Python) the right tool is cloud-init (user_data); for everything else, patterns A or B.

  1. Migrating the staging environment from Lesson 8.4

If you have the environment from Lesson 8.4 up, don't run staging-terraform.yml on top of it: Terraform doesn't know about those resources and would create another VPC with the same network (and another three instances). There are two paths:

Path How When
Destroy and recreate ansible-playbook staging-aws-destroy.yml -e confirm=aurora-staging and then staging-terraform.yml Ephemeral environments like Aurora's staging (recreated in minutes)
Import import { to = aws_vpc.this, id = "vpc-..." } blocks in the .tf files and tofu plan until there are no differences Resources that can't be recreated (production, data)

Aurora destroys and recreates. Then it retires the playbooks from Lesson 8.4, which are no longer how the environment is managed:

git rm staging-aws.yml staging-aws-destroy.yml
git add terraform/staging/*.tf terraform/staging/.terraform.lock.hcl cloud/aws-staging.yml \
        staging-terraform.yml staging-configure.yml .gitignore
git commit -m "Staging on AWS with OpenTofu/Terraform run from Ansible"
git push

The amazon.aws collection stays in collections/requirements.yml: what you learned with its modules is still useful for one-off operations, and its aws_ec2 inventory plugin will be the basis of Lesson 10.2.

  1. When to choose each approach

Situation Recommendation
Many interdependent cloud resources (networks, load balancers, managed databases, DNS) Terraform/OpenTofu for provisioning
Configuring operating systems and applications Ansible
A few cloud resources alongside a lot of configuration, and a team that only knows Ansible Ansible only (Lesson 8.4)
A platform team with Terraform and a systems team with Ansible Pattern A, with the outputs or a dynamic inventory as the contract
A single entry point with approvals and history in AWX Pattern B (Ansible runs Terraform), with remote state
Data center infrastructure (existing VMs, network devices) Ansible
Running Ansible from Terraform with local-exec Avoid it
An open source license is mandatory OpenTofu instead of Terraform

And one rule for any combination: every resource has a single owner. If Terraform manages the security groups, Ansible mustn't touch them (and vice versa), or each tool will undo the other's changes.

Common Mistakes and Tips

  • Failed to find required executable "terraform" or similar: the module can't find the binary; set the absolute path in binary_path.
  • Terraform plan could not be created / init errors: run tofu init and tofu plan by hand in terraform/staging/ to see the full message; it's usually a variable without a value or a provider that hasn't been downloaded.
  • Duplicate resources after "losing" the state: someone deleted terraform.tfstate or ran it from another clone of the repository. That's why remote state is mandatory as soon as an environment is shared.
  • Error acquiring the state lock: another run is in progress (or a previous one ended badly and left the lock). Make sure nobody is applying before forcing the unlock (tofu force-unlock).
  • The configuration play finds no hosts: the output name doesn't match (outputs.servers.value) or provisioning ended with state: absent.
  • Configuration changes that Terraform "undoes": two tools managing the same resource. Decide on a single owner.
  • Tip: always review the plan (--check in the playbook or tofu plan) before applying changes that could replace resources (Terraform marks them as -/+): replacing an instance means losing everything it had.

Exercises

Exercise 1: which tool?

For each task, state whether at Aurora it would be done by Terraform, Ansible or both, and why: (a) create a DNS record staging.aurora-store.example pointing to the first web server; (b) change nginx's worker_connections; (c) add a managed database (RDS) for staging; (d) create the aurora user inside that database; (e) roll out system patches every week.

Exercise 2: one more output

Add a web_public_ips output to the Terraform project with the list of the web servers' public IPs, and a task at the end of the first play in staging-terraform.yml that shows it only with the info tag.

Exercise 3: scaling down to one web server

You want to go down to a single web server in staging. What do you change, what will --check show you and which instance will be destroyed? What would happen to that instance's Ansible configuration?

Solutions

Exercise 1. (a) Terraform: it's a resource in the DNS API (Route 53 or another) that depends on the IP of an instance created by Terraform; within the same project, the reference is direct. (b) Ansible: it's configuration inside the server (nginx_worker_connections in the inventory). (c) Terraform: a cloud resource with a network, a security group and parameters, a typical provisioning job; its administrator password would go into a secrets manager or be marked as sensitive. (d) Ansible, with community.postgresql.postgresql_user from a host that can reach the database (or by delegating): it's service configuration, just as the postgresql role does on db1; Terraform has a PostgreSQL provider, but you'd be mixing responsibilities. (e) Ansible: upgrade.yml scheduled in AWX (Lesson 5.8); it's maintenance inside the server.

Exercise 2. In terraform/staging/outputs.tf:

output "web_public_ips" {
  value = aws_instance.web[*].public_ip
}

In the first play of staging-terraform.yml:

    - name: Show the public IPs of the web servers
      ansible.builtin.debug:
        msg: "{{ aurora_staging_tf.outputs.web_public_ips.value | default([]) }}"
      tags: [never, info]

The aws_instance.web[*].public_ip (splat) expression returns the list of that attribute for all the instances of the resource with count. With ansible-playbook staging-terraform.yml --tags info only the tagged task would run… and the Terraform module, which doesn't have that tag, wouldn't: the variable wouldn't exist, which is why it has default([]). To actually see it, run ansible-playbook staging-terraform.yml --tags all,info.

Exercise 3. You change aurora_staging_web_count: 1 in cloud/aws-staging.yml. With ansible-playbook staging-terraform.yml --check --diff, the plan will show 1 resource to destroy: aws_instance.web[1] (aurora-staging-web-2), because count removes the highest indexes. When it's applied, Terraform terminates that instance and the servers output no longer includes it, so add_host doesn't add it and the configuration play doesn't touch it. All the configuration Ansible had applied to it disappears with the instance, which is correct: the machines in an environment like this are replaceable, and their configuration lives in the code, not on the server.

Conclusion

You've seen that Terraform/OpenTofu and Ansible don't compete: the former provisions, with a state that lets it plan, order dependencies and destroy precisely; the latter configures and orchestrates processes. You know the three integration patterns: Terraform creates and Ansible reads its outputs (with a template, the cloud.terraform inventory plugins or the cloud's dynamic inventory); Ansible runs Terraform with community.general.terraform and turns its outputs into hosts with add_host; and the local-exec provisioner, which is best avoided. You've rebuilt Aurora's staging environment with OpenTofu in terraform/staging/ (with default_tags, count, ignore_changes and a servers output as the contract) and with pattern B in staging-terraform.yml + staging-configure.yml, you know why the state must be remote, encrypted and locked as soon as it's shared, and you have criteria for choosing. With this you close Module 8: Aurora Store manages containers with Docker, deploys to Kubernetes, verifies and releases with a CI/CD pipeline, and creates cloud environments with Ansible and Terraform. But look at the repository: at the root, the lab playbooks sit alongside apiservers.yml, kubernetes.yml, catalog-image.yml, staging-terraform.yml and staging-configure.yml; there are variables in inventory/, in group_vars/ next to the playbooks and in cloud/; there are ee/, ci/, .gitea/, terraform/ and lab/ directories; and a staging environment that still can't receive the full configuration because the inventory data is tied to the lab. It has grown a lot and needs order. In Module 9: Ansible Best Practices you'll start with the lesson Code Organization, where you'll reorganize aurora-infra with inventories separated by environment (staging and production), each with its own Vault identity, and a directory structure designed to grow without losing control.

Ansible Course: From Beginner to Advanced

Module 1: Introduction to Ansible

Module 2: Ansible Fundamentals

Module 3: Playbooks

Module 4: Roles

Module 5: Advanced Playbook Techniques

Module 6: Ansible Galaxy

Module 7: Ansible Tower, AWX and Automation Platform

Module 8: Ansible for DevOps

Module 9: Ansible Best Practices

Module 10: Advanced Ansible Topics

Module 11: Final Project

© Copyright 2026. All rights reserved