Resources Infrastructure

Ansible vs Terraform: Core Differences and When to Use Both

Compare Ansible and Terraform for infrastructure automation. Learn how state management, provisioning, and configuration differ, and how to use both.

TL;DR — Terraform provisions infrastructure through cloud APIs and tracks it in a state file; Ansible configures running hosts over SSH without state. Choose Terraform for networks, clusters, and managed services, Ansible for OS configuration, patching, and deployments. Most teams run both, and Kestra chains them in one approved workflow.

Teams building cloud platforms routinely pit Ansible against Terraform as if choosing one eliminates the need for the other. This confusion usually surfaces when an operations team attempts to provision cloud networks using Ansible modules, or when platform engineers attempt to configure operating system services using Terraform local-exec provisioners. Both approaches quickly degrade into brittle, unmaintainable scripts that fail silently during partial updates.

The division between the two tools is architectural rather than competitive. Terraform provisions immutable cloud infrastructure using a declared dependency graph, while Ansible executes configuration and operational runbooks across mutable hosts. This page compares them head to head and gives the criteria for choosing each.

Ansible vs Terraform at a glance

Both are usually filed under Infrastructure as Code, but they solve different problems in the infrastructure lifecycle.

DimensionAnsibleTerraform
Primary paradigmConfiguration management and operational task executionInfrastructure as Code (IaC) and cloud provisioning
ArchitectureAgentless, pushes tasks over SSH, WinRM, or APIsAPI-driven via declarative provider plugins
State modelStateless by default; gathers facts dynamically at runtimeStateful; records resources in a .tfstate backend
Configuration languageYAML playbooks with Jinja2 templatingHashiCorp Configuration Language (HCL)
Execution styleProcedural task lists within plays; runs step by stepPurely declarative dependency graph parsed as a DAG
Drift handlingCheck mode (--check --diff) reports what would change on each hostterraform plan (or plan -refresh-only) compares state and real resources
Rollback mechanismNone built in: compensating tasks or a re-run of a known-good playbookNone built in: revert the code and apply again (or destroy)
Inventory handlingDynamic inventory plugins query cloud APIs and CMDBsProduces outputs consumed by downstream automation
Open-source licenseGPLv3 (Red Hat upstream project)Business Source License; OpenTofu is the MPL-2.0 fork
Commercial platformRed Hat Ansible Automation Platform (AAP)HCP Terraform and Terraform Enterprise (IBM company)
Sweet spotOS hardening, software deployment, patching, network devicesVPCs, Kubernetes clusters, managed databases, VMs

Provisioning vs configuration: the architectural boundary

The primary boundary between Ansible and Terraform lies in whether an automation task targets an infrastructure control plane API or an operating system shell.

Terraform was engineered from the ground up for lifecycle management of cloud resources. It interacts with cloud providers, hypervisors, and SaaS APIs by translating HashiCorp Configuration Language into structured HTTP requests. When you declare an AWS EC2 instance, a Google Cloud VPC, or an Azure virtual network in Terraform, the engine calculates the required API calls, executes them in parallel where dependencies permit, and stores the resulting resource identifiers. Terraform manages the creation, modification, and destruction of these resources over time, ensuring that deleting a resource from the HCL definition results in a corresponding API call to remove it from the cloud provider.

Ansible was engineered for configuration management and remote systems administration. Instead of maintaining an API-level inventory of cloud primitives, Ansible connects directly to existing operating systems over SSH for POSIX systems or WinRM for Windows hosts. It requires no persistent agent on the target machine; instead, it executes Python or PowerShell modules ephemerally on the remote system to ensure the declared state is achieved, such as installing packages, placing configuration files, managing system users, and restarting daemons.

Problems arise when teams push either tool across this architectural boundary. Using Terraform remote-exec or local-exec provisioners to install packages or run shell commands binds the lifecycle of operating system configuration to cloud resource creation. If a package installation fails inside a Terraform provisioner, the resource is marked as tainted in state, often forcing a full destroy-and-recreate cycle on the next run. Conversely, using Ansible cloud modules (such as amazon.aws.ec2_instance) to provision infrastructure forces a procedural engine to emulate cloud topology. Ansible does not maintain an internal dependency graph of cloud resources; deleting an instance from an Ansible playbook does not destroy the live cloud resource unless an explicit state: absent play is written and maintained.

State management: Terraform’s state file vs Ansible’s live facts

State management represents the most pronounced technical difference between Terraform and Ansible, dictating how each tool determines what actions to execute.

Terraform relies on a state file (terraform.tfstate), stored either locally or in remote backends such as Amazon S3, Google Cloud Storage, or HashiCorp HCP Terraform. The state file maps every managed resource in the code to its real-world ID and attributes. When you execute a run, Terraform performs three steps:

  1. It refreshes the state by querying cloud APIs for all tracked resources.
  2. It compares the live API response against the declared HCL configuration.
  3. It generates an execution plan that specifies exact additions, updates in place, or destructive replacements.

Because Terraform maintains this absolute ledger, it handles resource destruction automatically. If you remove a database subnet from your HCL file, Terraform inspects the state file, notes that the resource is currently managed but no longer declared, and schedules a deletion API call.

Ansible uses a stateless operational model. It does not maintain a central database or file recording previous runs. When an Ansible playbook runs against an inventory of servers, its first operational task is typically fact gathering (setup module). Ansible inspects the live host to gather IP addresses, kernel versions, disk partitions, and installed software. Each task in the playbook then evaluates whether the remote host matches the target configuration:

- name: Ensure Nginx is installed and active
hosts: webservers
tasks:
- name: Install nginx package
ansible.builtin.package:
name: nginx
state: present
- name: Start and enable nginx service
ansible.builtin.service:
name: nginx
state: started
enabled: true

If the package is missing, Ansible installs it; if it is already present, Ansible marks the task as ok and proceeds. Because Ansible does not track what it previously created, it cannot detect deletions. If you remove the Nginx task from your playbook, Ansible simply stops evaluating Nginx on subsequent runs; it will not uninstall the package or stop the service.

This difference directly affects drift detection. Terraform detects configuration drift across infrastructure APIs via terraform plan (or terraform plan -refresh-only), alerting teams whenever a cloud resource was modified outside of code. To explore automated drift reconciliation, refer to our playbook on Terraform drift detection. Ansible detects configuration drift on host operating systems using check mode (ansible-playbook --check --diff), which executes tasks in dry-run mode to report configuration changes without applying them.

Execution models: declarative graphs vs sequential plays

The internal execution engine of each tool determines how tasks are scheduled, parallelized, and ordered.

Terraform operates on a Directed Acyclic Graph (DAG). When you run terraform apply, Terraform parses all .tf files in the module, extracts implicit and explicit dependencies between resources, and builds an execution graph. For instance, if resource B references aws_vpc.main.id from resource A, Terraform knows it must create resource A before resource B. Resources that share no dependencies are provisioned concurrently across multiple worker threads. The physical order in which blocks are written inside the .tf files is completely ignored.

Ansible operates on an imperative, sequential execution model. Playbooks are evaluated strictly from top to bottom. While individual tasks declare an idempotent desired state, the order of tasks matters.

For example, if one task installs a database server and the next creates a database user, swapping their order in the YAML file breaks execution. Ansible supports parallel execution across different hosts using the forks parameter, but within any single host, tasks run in strict linear succession.

Error handling reflects these execution models. If a Terraform provider call encounters an API error, Terraform halts dependent branches of the graph while completing unblocked branches, leaving the state file updated with all successfully created resources. When an Ansible task fails on a host, that host is immediately removed from the active play rotation unless the task specifies ignore_errors: true or routes execution through a block...rescue structure.

Licensing and governance: BSL vs open source

Licensing models and vendor ownership have become central evaluation criteria for platform engineering teams choosing their automation stack.

In 2023, HashiCorp moved Terraform from the open-source Mozilla Public License (MPL-2.0) to the Business Source License (BSL). The BSL is a source-available license that permits free production use and development, provided the deployment does not compete commercially with HashiCorp’s paid cloud or enterprise offerings. In February 2025, IBM completed its acquisition of HashiCorp. For organizations that need an OSI open-source license, the Linux Foundation hosts OpenTofu, an MPL-2.0 fork of the last open-source Terraform release. Commercial hosted execution for Terraform centers on HCP Terraform and Terraform Enterprise.

Ansible remains open-source software licensed under the GNU General Public License v3.0 (GPLv3). Red Hat governs the upstream Ansible Community project and packages commercial automation under the Red Hat Ansible Automation Platform (AAP). The commercial AAP platform includes the automation controller (formerly Ansible Tower) for web-based job execution, role-based access control, dynamic inventory management, and credential isolation. Teams seeking alternative management platforms for Ansible often evaluate options detailed in our overview of Ansible Tower alternatives.

Ready to orchestrate your infrastructure?

When to choose Terraform

Choose Terraform (or OpenTofu) as your primary tool when the objective is managing infrastructure lifecycles through cloud and data center APIs:

  • Greenfield cloud provisioning: Deploying entire cloud topologies, including virtual private clouds (VPCs), subnets, routing tables, internet gateways, and security groups.
  • Managed cloud services: Managing resources that have no underlying operating system accessible over SSH, such as Amazon S3 buckets, Google Cloud BigQuery datasets, Azure SQL databases, and Cloudflare DNS records.
  • Kubernetes cluster infrastructure: Provisioning managed control planes (EKS, GKE, AKS) along with their supporting node groups, IAM roles, and storage classes.
  • Multi-cloud resource lifecycles: Standardizing provisioning workflows across AWS, GCP, Azure, and on-premise VMware environments using a uniform declarative syntax and state engine.
  • GitOps infrastructure pipelines: Enforcing strict pull-request workflows where terraform plan output is reviewed and approved before applying changes to production environments.

In every case, running Terraform from Kestra adds the approval step, secrets, retries, and a log of each apply, without a CI script around it.

When to choose Ansible

Choose Ansible when the objective is managing software configuration, security posture, and operations inside running servers and network hardware:

  • Operating system hardening: Applying CIS benchmarks, configuring firewall rules (iptables / ufw), managing SSH keys, and provisioning system users across heterogeneous Linux and Windows fleets.
  • Middleware and software installation: Installing database clusters, web servers, runtime environments, and monitoring agents onto virtual machines or bare-metal systems.
  • Patch management and rolling updates: Orchestrating security updates across server groups with health checks, removing instances from load balancers sequentially, updating packages, and re-attaching them.
  • Network switch and appliance automation: Configuring interfaces, VLANs, and routing protocols on Cisco, Arista, or Juniper hardware that cannot run external agents.
  • Ad-hoc sysadmin operations: Executing zero-downtime maintenance procedures, gathering audit artifacts, or triggering one-off operational runbooks across distributed fleets.

Running playbooks from Kestra gives each run a schedule or event trigger, an approval gate when needed, and logs in one place. For other configuration tools, see Ansible alternatives.

When to use both tools together

Most teams do not choose: Terraform provisions the machines and networks and outputs their addresses, then Ansible configures the software on them. The integration patterns (provisioners, dynamic inventory, passing outputs) are covered in Terraform and Ansible: how to use them together.

How to orchestrate Ansible and Terraform with Kestra

Chaining the two with shell wrappers or local-exec leaves no audit log, no retries, and no way to pause for review. Kestra runs both as tasks of one flow.

The flow below plans the change, waits for an engineer to approve it, then applies it and configures the new host with Ansible in the same working directory.

id: terraform-then-ansible
namespace: platform.infrastructure
inputs:
- id: environment
type: SELECT
values:
- staging
- production
defaults: staging
tasks:
- id: plan
type: io.kestra.plugin.core.flow.WorkingDirectory
tasks:
- id: clone
type: io.kestra.plugin.git.Clone
url: https://github.com/your-org/infrastructure.git
branch: main
- id: terraform_plan
type: io.kestra.plugin.terraform.cli.TerraformCLI
beforeCommands:
- terraform init -input=false
commands:
- terraform plan -input=false -no-color -var="environment={{ inputs.environment }}" -out=tfplan
outputFiles:
- tfplan
env:
AWS_ACCESS_KEY_ID: "{{ secret('AWS_ACCESS_KEY_ID') }}"
AWS_SECRET_ACCESS_KEY: "{{ secret('AWS_SECRET_ACCESS_KEY') }}"
AWS_DEFAULT_REGION: eu-west-1
- id: approve
type: io.kestra.plugin.core.flow.Pause
pauseDuration: PT2H
behavior: CANCEL
- id: apply_and_configure
type: io.kestra.plugin.core.flow.WorkingDirectory
tasks:
- id: clone_again
type: io.kestra.plugin.git.Clone
url: https://github.com/your-org/infrastructure.git
branch: main
- id: terraform_apply
type: io.kestra.plugin.terraform.cli.TerraformCLI
inputFiles:
tfplan: "{{ outputs.terraform_plan.outputFiles['tfplan'] }}"
beforeCommands:
- terraform init -input=false
commands:
- terraform apply -input=false tfplan
- printf '[web]\n%s\n' "$(terraform output -raw web_private_ip)" > inventory.ini
env:
AWS_ACCESS_KEY_ID: "{{ secret('AWS_ACCESS_KEY_ID') }}"
AWS_SECRET_ACCESS_KEY: "{{ secret('AWS_SECRET_ACCESS_KEY') }}"
AWS_DEFAULT_REGION: eu-west-1
- id: ansible_configure
type: io.kestra.plugin.ansible.cli.AnsibleCLI
inputFiles:
id_rsa: "{{ secret('SSH_PRIVATE_KEY') }}"
env:
ANSIBLE_HOST_KEY_CHECKING: "False"
commands:
- chmod 600 id_rsa
- ansible-playbook -i inventory.ini --private-key id_rsa site.yml
errors:
- id: alert
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text": "Provisioning for {{ inputs.environment }} failed (execution {{ execution.id }})."}

What the flow shows:

  • Apply what was reviewed: the plan is in the execution logs and saved as tfplan; nothing changes until an engineer resumes the run, and the apply step runs that saved plan, not a new one. If the state changed in the meantime, Terraform rejects the stale plan instead of applying something else. With behavior: CANCEL, an unanswered approval cancels the run after two hours instead of applying.
  • One handoff, no wrapper script: Terraform writes the new host’s address to inventory.ini, and Ansible reads it from the same working directory. State lives in the repository’s remote backend, so the plan and apply steps see the same infrastructure.
  • Tools in their own containers: Terraform and Ansible run in their default images, so the Kestra host needs neither binary.
  • Secrets and alerts: cloud keys and the SSH key come from Kestra secrets, and any failure posts to Slack.

See Terraform orchestration and Ansible orchestration for more patterns, and the Terraform and Ansible plugin references.

Terraform, Ansible and Kubernetes, orchestrated from one place.

Frequently asked questions

Find answers to your questions right here, and don't hesitate to Contact Us if you couldn't find what you're looking for.