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.
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
| Terraform | Ansible | |
|---|---|---|
| Main job | Provisioning: create, change and delete infrastructure | Configuration management, deployment and task automation |
| Style | Declarative: describe the end state | Mostly procedural: ordered tasks, each idempotent |
| Language | HCL (HashiCorp Configuration Language) | YAML playbooks with Jinja2 templating |
| How it connects | Cloud and service APIs, through providers | SSH or WinRM to hosts, plus APIs for cloud and network gear |
| Agent needed? | No | No (agentless) |
| State | Keeps a state file mapping config to real resources | No state file; checks the target each run |
| Change preview | terraform plan shows every change before apply | --check and --diff dry runs, module support varies |
| Drift handling | Detects and corrects drift on the next plan | Re-applies desired settings when run |
| Deletes things it no longer manages? | Yes: remove from code, apply, it's destroyed | No: you write explicit tasks to remove things |
| Best at | Cloud resources, networks, managed services, Kubernetes clusters | OS setup, app deployment, patching, network device config, ad hoc ops |
| Licence | Business Source License 1.1 (OpenTofu fork is MPL 2.0) | GPLv3 |
| Owner | HashiCorp, part of IBM | Red 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
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:
- `terraform init` downloads the providers and modules.
- `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.
- `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: trueRun 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:
| Task | Better choice | Why |
|---|---|---|
| Create a VPC, subnets and security groups | Terraform | Dependency graph, plan, clean deletes |
| Launch and resize cloud databases | Terraform | Full lifecycle, drift detection |
| Install packages and set up users on 200 servers | Ansible | Built for OS configuration |
| Rolling app deployment with health checks | Ansible | Ordered steps, batches with serial |
| Configure routers and switches | Ansible | Large set of network vendor modules |
| Manage DNS records and CDN settings | Terraform | Providers for most DNS and CDN services |
| Patch servers monthly | Ansible | Repeatable task runs |
| Build a Kubernetes cluster on a cloud | Terraform | Cluster, node groups and networking as resources |
| Deploy apps into Kubernetes | Neither by default | Helm, Argo CD or Flux usually fit better |
| One-off fix across all hosts | Ansible | Ad 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
Here is how Terraform and Ansible work together in a typical pipeline:
- Terraform provisions. It creates the network, the instances, the load balancer and the database.
- Terraform hands over the host list. Outputs, tags or a dynamic inventory tell Ansible which hosts exist and which groups they belong to.
- Ansible configures. It installs packages, deploys the app and registers hosts with monitoring.
- Both run from CI. A pipeline runs
terraform planfor 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/ansibleprovider for Terraform. It lets Terraform declare inventory hosts and groups, and thecloud.terraformAnsible 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
shellandcommandtasks run every time unless you addcreatesorchanged_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.