Terraform vs Ansible: Resource Ownership, Plans and Handoffs

Terraform vs Ansible is primarily a choice about what you need to change: cloud resources, the software inside running machines, or both. Red Hat’s comparison describes a useful division: Terraform provisions infrastructure, then Ansible configures it and handles continuing operations. Choose Terraform when resource lifecycle is the main problem; choose Ansible when an existing fleet needs repeatable configuration. Combine them when there is a clear handoff between those responsibilities.

The important design decision is ownership. A successful Terraform run can create the right servers while an Ansible run targets the wrong inventory. Conversely, a correct playbook can keep an application healthy while a separate infrastructure change replaces its host. The integration needs an explicit contract for which resources exist, which addresses are exported and which configuration runs against them.

Google · Preferred Sources

Don't miss new tech stories on Google

Add Tech Insider once in the Google app and our stories appear in your news suggestions.

Add Now

Assign each changing object a single owner

Red Hat describes Terraform’s HCL as a declaration of desired infrastructure and Ansible’s YAML as an ordered sequence of tasks. That distinction helps explain the workflow, but it is incomplete as a selection rule. The Ansible playbook documentation says most modules check whether their desired state is already satisfied. A task can therefore be part of an ordered procedure and still make no change when repeated.

ResponsibilityTerraformAnsible
Infrastructure definitionHCL configuration describes managed resourcesYAML playbooks describe tasks and targeted hosts
Persistent resource recordState tracks managed infrastructure and its configurationTasks inspect target systems; no Terraform-style resource state file
Typical lifecycle roleProvision and manage cloud resourcesConfigure running systems and orchestrate operations
Execution structurePlan proposed resource changes, then apply themRun plays and their tasks in order
RepeatabilityCompare configured resources with tracked infrastructureIdempotency depends on the selected modules and tasks
Combined workflowSupply provisioned resource informationConsume the selected hosts and configure them

For a web service, a sensible boundary gives Terraform the virtual machines and network resources and gives Ansible the packages, configuration files and service state inside those machines. Avoid having both configurations independently manage the same cloud object. Otherwise, a later run can undo an intentional change made by the other tool, even though both runs behave as their authors intended.

Ansible can also provision resources, so an existing Ansible deployment does not need Terraform merely to qualify as infrastructure as code. Add it when persistent resource ownership and the plan/apply workflow solve a problem you actually have. Similarly, a container platform may already own application rollout; the Docker and Kubernetes comparison helps place that application layer separately from cloud provisioning.

A plan and a check answer different questions

The Terraform plan command distinguishes a speculative preview from a saved execution plan. Running terraform plan lets a reviewer inspect proposed changes. Saving with -out produces a plan file that can later be passed to terraform apply. Running apply without that file creates a new plan, so it is not the same approval artifact.

ControlTerraformAnsible
Previewterraform plan shows proposed infrastructure changesansible-playbook –check predicts changes supported by the tasks
File differencesResource changes appear in the plan–diff shows small file and template differences
Preflight selectionInspect resource addresses and proposed actions–list-hosts shows targets; –syntax-check checks playbook syntax
Machine-readable change signalWith -detailed-exitcode: 0 means no changes, 1 means error, 2 means changesRead task results and the per-host recap in the playbook output
Default parallel work10 concurrent graph operations5 parallel processes

The Ansible command reference describes check mode as an attempt to predict some changes. Use it alongside host selection and syntax validation. The playbook documentation also warns that not every module or playbook is idempotent. A shell task that blindly appends a line and a module that maintains a desired file state can behave differently on the next run.

In a delivery pipeline, preserve the distinction between a changed plan and a failed plan. Terraform’s detailed exit code 2 represents a successful preview with changes; treating every nonzero result as a tool failure hides that useful signal. Conversely, an empty infrastructure diff says nothing about whether the application’s configuration is correct. The Ansible run still has its own targets and task outcomes to review.

Keep the plan alongside the change request with restricted access: HashiCorp says saved plans can contain sensitive data in cleartext even when terminal output conceals it. Approval and artifact retention therefore belong together. A GitHub and GitLab comparison is relevant when choosing the repository and review platform around this workflow, rather than changing the responsibility split between Terraform and Ansible.

Bring existing resources into state before handing them off

Moving provisioning from Ansible to Terraform should start by adopting the resources you intend to keep. HashiCorp’s resource import documentation requires an import block with a resource identity and a matching destination resource block. An existing machine is not automatically under Terraform management merely because a similar resource appears in an HCL file.

For an existing AWS instance, the following import declaration uses an input containing that instance’s actual ID. Run it inside an initialized project with its AWS provider and credentials configured. The destination address must match the resource definition you write or generate; this example deliberately does not substitute a sample machine ID for a real target.

variable "existing_instance_id" {
  type = string
}

import {
  to = aws_instance.web_server
  id = var.existing_instance_id
}

For a destination resource that is not yet in configuration, the documented generation route is:

terraform plan -generate-config-out=imported.tf

Review the generated resource configuration before applying the import. In particular, investigate any proposed replacement or deletion rather than accepting it as a normal part of adoption. Move provisioning ownership only after the resource identity, intended configuration and resulting plan agree. Then remove the old provisioning task from the Ansible workflow while retaining the host-configuration tasks that still belong there.

State storage needs its own preparation. The Terraform S3 backend documentation says locking is opt-in: use_lockfile = true enables its lockfile mechanism, while DynamoDB-based locking is deprecated. HashiCorp also recommends bucket versioning to recover state after accidental deletion or human error. The backend assumes the bucket already exists, so create and protect that storage before it becomes the team’s shared state location.

State recovery and application rollback solve different problems. Restoring a state record does not itself run the infrastructure changes needed to restore a service. For a configuration rollback, review the desired configuration and the resulting plan; for an Ansible deployment, prepare the previous application configuration and an appropriate service transition. Keeping that distinction explicit avoids treating a recovered file as a recovered production system.

Pass only the hosts Ansible should configure

The handoff can be small and inspectable. Define a root-module output named web_server_ips containing only the intended web hosts’ IP addresses. HashiCorp’s Terraform output reference recommends JSON for automation and explains that the command exposes root-module outputs. Choose addresses reachable from the Ansible controller, rather than exporting every instance in the workspace.

For the imported instance above, a public-address output would take this form. Use it only where that address exists and is reachable by the controller; otherwise select the appropriate reachable address for your environment.

output "web_server_ips" {
  value = [aws_instance.web_server.public_ip]
}

This Bash example requires Terraform, jq and an existing configured workspace. It writes the inventory group once, rejects an empty or malformed address list, and replaces the inventory only after successful generation. Its address character check accepts IPv4 and IPv6-style strings; use an IP parser as well if the output can come from untrusted input. The output should contain host addresses only, never credentials, because Terraform’s JSON output can reveal sensitive values.

set -euo pipefail
umask 077
inventory_tmp=$(mktemp ./inventory.ini.XXXXXX)
trap 'rm -f "$inventory_tmp"' EXIT
terraform output -json web_server_ips |
  jq -er '
    if type == "array" and length > 0 and
       all(.[]; type == "string" and test("^[0-9A-Fa-f:.]+$"))
    then "[web_servers]\n" + join("\n")
    else error("Expected a nonempty array of IP address strings")
    end' > "$inventory_tmp"
mv "$inventory_tmp" inventory.ini
ansible-playbook -i inventory.ini configure-web.yml --syntax-check
ansible-playbook -i inventory.ini configure-web.yml --list-hosts

For the configuration side, this playbook assumes Debian or Ubuntu targets, working Ansible access and privilege escalation, and a complete, reviewed nginx.conf.j2 template beside the playbook. Save it as configure-web.yml. It preserves the useful package, template, service and handler sequence:

---
- name: Configure web servers
  hosts: web_servers
  become: true
  tasks:
    - name: Install Nginx
      ansible.builtin.apt:
        name: nginx
        state: present
        update_cache: true
    - name: Deploy Nginx configuration
      ansible.builtin.template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
        owner: root
        group: root
        mode: "0644"
        validate: "/usr/sbin/nginx -t -c %s"
      notify: Restart Nginx
    - name: Ensure Nginx is running
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: true
  handlers:
    - name: Restart Nginx
      ansible.builtin.service:
        name: nginx
        state: restarted

Ansible’s handler documentation explains why the restart belongs there: a changed task notifies the handler, and repeated notifications coalesce into a single execution when handlers run. An unchanged template does not request a restart. The template validation command in this example checks the candidate Nginx configuration before replacing the destination file; adapt its binary path and template dependencies to the target installation.

After checking the inventory, preview the playbook on a selected test host with --check --diff --limit and that host’s inventory name. Apply the reviewed configuration to that host before broadening the target set. This separates three failures that otherwise look like one deployment problem: incorrect provisioned resources, an incorrect host list and an incorrect application configuration.

Separate CLI licensing from managed control

Terraform’s repository license file specifies Business Source License 1.1 and explicitly excludes internal organizational use from its definition of a competitive offering. The Ansible CLI documentation identifies its license as GPLv3+. Those terms describe the software; a managed workflow platform is a separate purchase.

Product or planPublished price or commercial modelWhat the comparison covers
IBM HCP Terraform EssentialsFrom $0.10 per resource/month; rated at $0.00013 per resource/hourCloud infrastructure workflow
IBM HCP Terraform StandardFrom $0.47 per resource/month; rated at $0.00064 per resource/hourCloud plan including HCP Waypoint
IBM HCP Terraform PremiumFrom $0.99 per resource/month; rated at $0.00135 per resource/hourCloud plan including HCP Waypoint
IBM Terraform EnterpriseCustom pricingSelf-managed product with premium support
Ansible community CLIGPLv3+ softwarePlaybook execution with a separately operated workflow
Red Hat Ansible Automation PlatformSubscription productSupported platform for centrally managed automation

The official Terraform pricing page publishes both monthly resource rates and hourly billing rates. Budget for the managed resource population and its usage, then compare the platform capabilities you need. A server count alone is a poor substitute for that inventory: the intended Terraform configuration may also own network and other infrastructure resources.

Red Hat describes Ansible Automation Platform as an orchestrator that can run tasks before Terraform provisioning and configure applications afterward. That is a meaningful enterprise choice when a team needs a central workflow around both tools. It should be evaluated against the work currently needed to operate the existing Ansible environment, rather than an invented fixed price for every deployment.

For alternatives within the resource-provisioning layer, the OpenTofu, Terraform and Pulumi comparison addresses that separate selection. The Terraform/Ansible decision remains operational: choose the owner of each resource, preserve a reviewable change process and make the host handoff explicit. Adding both tools is worthwhile when it closes those responsibilities; a second tool with overlapping ownership adds another place for configuration to diverge.

Nadia Dubois

Nadia Dubois

AI, software and the business of tech

Nadia Dubois covers AI, software and the business of tech for Tech Insider: AI models and the products built on them, developer and productivity software, pricing, and the company decisions and regulation that shape the industry.

View all articles