Dev tools

Terraform vs Ansible: Which Tool for Which Job?

Terraform vs Ansible: Terraform creates infrastructure, Ansible configures what runs on it. How each works, code side by side, and how to combine them.

By OmniAI Editorial · Nov 22, 2026 · 12 min read

In Terraform vs Ansible, the short answer is that they solve different halves of the same job. Terraform creates and changes infrastructure (networks, virtual machines, databases, DNS, cloud services) by comparing a declared target state with what exists and applying the difference. Ansible configures and operates systems (installs packages, edits files, starts services, runs deployments and one-off tasks) by running ordered tasks over SSH or an API. Most teams that use both let Terraform build the servers and Ansible set them up.

They overlap at the edges. Ansible has cloud modules that can create resources, and Terraform can run scripts on new machines. This guide compares them in a table, shows the same job in both languages, explains how they work together, covers which is better for common tasks including network automation, and lists the mistakes that come from using one for the other's job. If you're new to the idea behind both, start with our guide to infrastructure as code.

Terraform vs Ansible at a Glance

TerraformAnsible
Main jobProvisioning: create, change and delete infrastructureConfiguration management, deployment and task automation
StyleDeclarative: describe the end stateMostly procedural: ordered tasks, each idempotent
LanguageHCL (HashiCorp Configuration Language)YAML playbooks with Jinja2 templating
How it connectsCloud and service APIs, through providersSSH or WinRM to hosts, plus APIs for cloud and network gear
Agent needed?NoNo (agentless)
StateKeeps a state file mapping config to real resourcesNo state file; checks the target each run
Change previewterraform plan shows every change before apply--check and --diff dry runs, module support varies
Drift handlingDetects and corrects drift on the next planRe-applies desired settings when run
Deletes things it no longer manages?Yes: remove from code, apply, it's destroyedNo: you write explicit tasks to remove things
Best atCloud resources, networks, managed services, Kubernetes clustersOS setup, app deployment, patching, network device config, ad hoc ops
LicenceBusiness Source License 1.1 (OpenTofu fork is MPL 2.0)GPLv3
OwnerHashiCorp, part of IBMRed Hat, part of IBM

One line to remember: Terraform owns the lifecycle of resources; Ansible owns what happens on and inside them.

What Is Terraform and Ansible Used For?

What is Terraform and Ansible used for in practice? Here are the typical jobs, split by who usually handles them.

Terraform is used to:

  • Create cloud networks, subnets, firewalls and load balancers.
  • Launch virtual machines, managed databases, object storage buckets and queues.
  • Set up Kubernetes clusters and cloud IAM roles and policies.
  • Manage SaaS settings that have providers, such as DNS, CDN, monitoring and identity providers.
  • Keep several environments (dev, staging, production) consistent from the same modules.

Ansible is used to:

  • Install and configure packages, users, files and services on Linux and Windows hosts.
  • Deploy applications and run rolling updates across server groups.
  • Patch fleets of servers and enforce security baselines.
  • Configure routers, switches and firewalls from many vendors.
  • Run one-off operations: restart a service everywhere, rotate a certificate, collect logs.

People often describe this as Day 0/1 vs Day 2. Terraform builds the platform on day 0 and 1. Ansible keeps it configured and runs operations from day 2 onward.

How Terraform Works

Two light panels. Top: a grey document, an ink arrow to a grey cylinder with an orange band, and an ink arrow to a grey cloud. Bottom: a grey document with three ink arrows to three grey servers.
Terraform compares code with state and calls cloud APIs; Ansible pushes ordered tasks to hosts over SSH.

Terraform reads .tf files that declare resources. Providers translate those declarations into API calls for AWS, Azure, Google Cloud, Kubernetes, Cloudflare and hundreds of other services. The core loop has three steps:

  1. `terraform init` downloads the providers and modules.
  2. `terraform plan` compares your code with the state (Terraform's record of what it created) and the real infrastructure, then prints what it will add, change or destroy.
  3. `terraform apply` makes those changes and updates the state.

A minimal example that declares a virtual machine:

resource "aws_instance" "web" {
  ami           = "ami-0abcdef1234567890"
  instance_type = "t3.micro"

  tags = {
    Name = "web-1"
  }
}

Terraform works out the order on its own from references between resources. Because it knows everything it manages, deleting the block and running apply destroys the instance. The state file is the part beginners underestimate. It must be stored remotely (for example in an S3 bucket or Terraform's own cloud service), locked during runs and protected, because it can contain secrets.

How Ansible Works

Ansible reads an inventory (the list of hosts and groups) and runs playbooks, which are YAML files of tasks. Each task calls a module, a small piece of code that brings one thing into the desired state and reports whether it changed anything. Ansible connects over SSH (or WinRM for Windows), copies the module over, runs it and cleans up. Nothing needs to be installed on the target except Python for most Linux modules.

The same "web server" job, configured with Ansible:

- name: Configure web servers
  hosts: web
  become: true
  tasks:
    - name: Install nginx
      ansible.builtin.apt:
        name: nginx
        state: present
        update_cache: true

    - name: Start and enable nginx
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: true

Run it with ansible-playbook -i inventory.ini site.yml. Modules are idempotent: if nginx is already installed and running, the second run reports "ok" and changes nothing. Tasks run in order, top to bottom, which makes multi-step procedures easy to read, such as "drain the node, upgrade the app, run migrations, put it back".

Declarative vs Procedural: Why It Matters

Terraform is declarative: you describe the result and it figures out the steps. Ansible is mostly procedural: you describe the steps, and each step is written to be safe to repeat.

That difference shows up in two places:

  • Removing things. If you remove a resource from Terraform code, Terraform deletes it. If you remove a task from a playbook, Ansible simply stops managing that thing. The package or file stays until you write a task with state: absent.
  • Knowing what exists. Terraform's state lets it show a full plan of changes across hundreds of resources. Ansible checks each host as it goes, so it has no single picture of "everything we own", but it also has no state file to protect, lock or repair.

Neither approach is better in general. Declarative suits long-lived infrastructure where you want exact control over what exists. Procedural suits sequences of operations and the messy reality inside operating systems.

Ansible vs Terraform: Which Is Better?

"Ansible vs Terraform which is better" is the most common question about the pair, and the honest answer is that it depends on the task:

TaskBetter choiceWhy
Create a VPC, subnets and security groupsTerraformDependency graph, plan, clean deletes
Launch and resize cloud databasesTerraformFull lifecycle, drift detection
Install packages and set up users on 200 serversAnsibleBuilt for OS configuration
Rolling app deployment with health checksAnsibleOrdered steps, batches with serial
Configure routers and switchesAnsibleLarge set of network vendor modules
Manage DNS records and CDN settingsTerraformProviders for most DNS and CDN services
Patch servers monthlyAnsibleRepeatable task runs
Build a Kubernetes cluster on a cloudTerraformCluster, node groups and networking as resources
Deploy apps into KubernetesNeither by defaultHelm, Argo CD or Flux usually fit better
One-off fix across all hostsAnsibleAd hoc commands and short playbooks

Which is easier to learn? Ansible usually feels easier at first, because YAML tasks read like a checklist and you can start with one playbook and an SSH key. Terraform's model of state, plans and resource graphs takes longer to grasp, but it pays off when infrastructure grows.

How Terraform and Ansible Work Together

A grey cloud with an ink arrow to a light list document, then an ink arrow to three grey servers, each with a gear beside it, the middle gear orange.
Terraform creates the servers and publishes them as inventory; Ansible then configures them.

Here is how Terraform and Ansible work together in a typical pipeline:

  1. Terraform provisions. It creates the network, the instances, the load balancer and the database.
  2. Terraform hands over the host list. Outputs, tags or a dynamic inventory tell Ansible which hosts exist and which groups they belong to.
  3. Ansible configures. It installs packages, deploys the app and registers hosts with monitoring.
  4. Both run from CI. A pipeline runs terraform plan for review, applies after approval, then runs the playbook.

There are three common ways to connect them:

  • Dynamic inventory from the cloud. Ansible's cloud inventory plugins (for example for AWS EC2) list instances by tag, so Terraform only needs to tag them correctly.
  • The Terraform provider for Ansible. Red Hat maintains an ansible/ansible provider for Terraform. It lets Terraform declare inventory hosts and groups, and the cloud.terraform Ansible collection reads them back as an inventory:
resource "ansible_host" "web1" {
  name   = aws_instance.web.public_ip
  groups = ["web"]
}
plugin: cloud.terraform.terraform_provider   # inventory.yml
  • Baked images. Use Ansible with Packer to build a machine image once, and let Terraform launch instances from that image. Servers then start ready, which speeds scaling and makes them replaceable rather than patched in place.

Avoid running Ansible from inside Terraform with local-exec provisioners for anything important. Terraform's own documentation treats provisioners as a last resort. They run once, aren't tracked in state and fail awkwardly.

Terraform vs Ansible for Network Automation

Terraform vs Ansible for network automation is one area where Ansible usually wins for device configuration. Ansible has collections for many network operating systems, such as Cisco IOS and NX-OS, Arista EOS, Juniper Junos and others. It can push configuration, take backups and check compliance over SSH or the device's API. Its ordered, step-by-step model also fits network change windows, where you configure, verify and roll back in sequence.

Terraform fits where the network is exposed as an API with a provider. That includes cloud networking, SD-WAN controllers, firewalls with management APIs and DNS and IP address management systems. Many network teams use Terraform for cloud and controller-managed networks and Ansible for device-level changes.

Licensing and Alternatives

In August 2023, HashiCorp moved Terraform from the open-source MPL 2.0 licence to the Business Source License. Using Terraform to manage your own infrastructure is still allowed; the restrictions target offering competing products. The community forked the last open version as OpenTofu, now hosted by the Linux Foundation under MPL 2.0 and largely compatible with Terraform configurations. IBM completed its acquisition of HashiCorp in February 2025, so both Terraform and Ansible (through Red Hat) now sit under IBM.

Other tools you'll see in the same comparison:

  • Pulumi: infrastructure as code in general-purpose languages (TypeScript, Python, Go).
  • AWS CloudFormation and Azure Bicep: provisioning for a single cloud, maintained by the provider.
  • Puppet, Chef and Salt: configuration management tools that typically use agents and a central server, as opposed to Ansible's agentless push.
  • Helm, Argo CD and Flux: deploying applications into Kubernetes, which neither Terraform nor Ansible is ideal for. Our guide to Docker vs Kubernetes covers the container side.

Which Should You Choose?

  • Mostly cloud resources, few long-lived servers: Terraform (or OpenTofu), plus container or serverless deployment.
  • Existing servers to configure, patch and deploy to: Ansible.
  • New cloud environment with VMs: both. Terraform for the platform, Ansible or baked images for the hosts.
  • Network device configuration: Ansible, with Terraform for cloud networking.
  • Small team, one tool to start: pick based on where most of your work is. If you'll create a lot of cloud resources, start with Terraform; if you'll manage a lot of servers, start with Ansible.

Common Mistakes

  • Managing the same resource with both tools. If Ansible changes a security group that Terraform owns, Terraform will revert it on the next apply. Give each resource one owner.
  • Using Ansible as a full provisioning tool for large clouds. Without state or a plan, deletes and dependencies become manual and error-prone.
  • Configuring servers with Terraform provisioners. Use Ansible, cloud-init or baked images instead.
  • Local Terraform state. Keep state in a remote, locked, access-controlled backend from day one.
  • Non-idempotent Ansible tasks. Raw shell and command tasks run every time unless you add creates or changed_when. Prefer real modules.
  • Long-lived snowflake servers. If servers are patched by hand between runs, both tools fight reality. Treat servers as replaceable where you can, and deploy changes gradually, for example with blue green deployment.

FAQ

Is Terraform the same as Ansible?

No. Both are infrastructure-as-code tools, but Terraform declares infrastructure and manages its full lifecycle through cloud APIs and a state file. Ansible runs ordered, idempotent tasks to configure and operate systems over SSH or APIs.

Can Ansible replace Terraform?

For small setups, partly. Ansible has cloud modules that can create resources. It lacks Terraform's state, plans and automatic deletes, which matter as infrastructure grows.

Can Terraform replace Ansible?

Only for simple bootstrapping. Terraform can pass startup scripts to new machines, but it isn't designed for ongoing configuration, patching or ordered operations on servers.

Do I need to learn both?

If you work with cloud infrastructure and servers, it helps. Many DevOps and platform roles expect Terraform for provisioning and Ansible for configuration, and the concepts transfer well.

Is OpenTofu a drop-in replacement for Terraform?

For most configurations, yes. OpenTofu started as a fork of Terraform and keeps compatibility with Terraform's language and providers. Check features added after the fork, which can differ between the two.

All articles

Read next

Language

EnglishEnglish · en TürkçeTurkish · tr DeutschGerman · de العربيةArabic · ar

Account

Enter your email. We’ll send you a sign-in link and a 6-digit code. No password needed.

Sign in

Theme

Language

Show our email address

To keep spam out of our inbox, please confirm your own email first. We will send you a 6-digit code.

We send codes only to these providers: gmail.com, googlemail.com, outlook.com, hotmail.com, live.com, msn.com, proton.me, protonmail.com, pm.me, icloud.com, me.com, mac.com, yahoo.com, aol.com, gmx.de, gmx.net, web.de, t-online.de, yandex.com, omniai.blog