Ansible and Terraform are two popular open-source tools commonly found in DevOps stacks. Although distinct in purpose, these tools somewhat overlap in functionality (primarily in terms of IaC capabilities), which often leads to confusion about when one tool is a better option than the other.
This article offers an in-depth Ansible vs Terraform comparison that outlines the main differences between the two solutions. We examine the pros and cons of both tools, explain their roles in infrastructure management, and show why the choice between Ansible and Terraform is not always an either-or dilemma.
What Is Ansible?
Ansible is an open-source Python-based automation tool that excels at configuring provisioned infrastructure, which includes tasks such as:
- Changing configuration files.
- Installing and updating software.
- Configuring runtime environments.
This Red Hat-owned tool also enables users to automate numerous IT processes, including:
- Provisioning of on-prem and cloud-based resources (servers, virtual machines, network devices, etc.).
- Orchestrating and deploying applications.
- Implementing security and compliance policies (e.g., a cloud security policy).
While the tool can provision resources, Ansible's functionalities gear more towards configuring existing infrastructure and automating repetitive tasks.
Main pros of Ansible
- There's a free and open-source version of the tool.
- An emphasis on simplicity and ease of use.
- Relies on the YAML (Yet Another Markup Language) syntax that's easy to read and write (especially when compared to XML or JSON).
- Highly scalable and allows users to manage a large number of systems with ease.
- Does not require the presence of agents on managed systems, which speeds up setups and minimizes performance degradation.
- A wide selection of helpful modules and plugins.
- Seamlessly integrates with various other DevOps tools (such as Jenkins, Docker, and Git).
- A large community of users and many available resources.
Main cons of Ansible
- Slow when collecting large volumes of data.
- Lacks a notion of state and does not track dependencies.
- Limited real-time feedback during code execution.
Ansible enables users to both automate and orchestrate configuration-related tasks. Our orchestration vs automation article explains the difference between the overlapping terms.
Here's an overview of Ansible's most notable features:
- A simple YAML syntax that enables declarative IaC capabilities.
- Top-tier configuration management and automation.
- A lightweight agentless architecture that does not require users to set up any software on target systems.
- Idempotent execution that enables users to execute the same instructions multiple times without changing the state of the target system.
- Simplified troubleshooting due to executing tasks sequentially and stopping once the tool identifies an error.
- SSH communication between the control node and the target systems.
- A large collection of pre-built modules (plus allows user-made modules written in Ruby or Python).
- Enables users to invert its setup to a pull architecture in which nodes request instructions from Ansible (typically done for scaling purposes).
- A large number of plugins (both custom and official).
Ansible shares some similarities with K8s. Learn the difference between the two automation tools in our Ansible vs Kubernetes article.
How Does Ansible Work?
The first step in using Ansible is to define an inventory of nodes (physical servers, virtual machines, cloud instances, etc.) you plan to manage with the tool. There's no need for any additional software or agents on the target machines. The inventory is either a:
- Simple text file.
- Dynamic inventory generated from an external system.
Once you define an inventory, start writing Ansible playbooks in YAML. Playbooks define the tasks required to reach the desired configuration on the target system.
Users write declarative code in playbooks, which means that you specify the desired state of the system and Ansible automatically performs the requested changes.
Ansible scripts are procedural, so they execute from top to bottom in the order they appear in the playbook. For example, to set up an Apache server on a VM as a root user, the playbook must first execute the user creation step before defining the server installation task.
The code in playbooks is quick and simple to write thanks to Ansible modules, small programs that perform specific tasks on target nodes, such as:
- Start a service on target systems.
- Install a package.
- Configure a system.
Ansible connects to nodes using an SSH connection and starts executing tasks once the user defines a playbook. You execute an Ansible playbook using the ansible-playbook command.
Once initiated, the tool connects to every target device in the inventory and executes tasks specified in the playbook.
Learn how to install Ansible on Rocky Linux.
What Is Terraform?
Terraform is an open-source IaC tool for creating, managing, and versioning on-prem and cloud infrastructure. This IaC tool from HashiCorp is primarily an orchestrator and focuses equally on provisioning both types of instances:
- Low-level instances (such as databases, load balancers, and networking).
- High-level instances (such as Kubernetes clusters or SaaS).
Terraform mainly focuses on infrastructure provisioning. The tool enables users to deploy various resources through the use of descriptive languages and models. Terraform uses its native HashiCorp Configuration Language (HCL), a declarative language with a JSON-like syntax.
Main pros of Terraform:
- A human-readable declarative syntax.
- Highly consistent and stable infrastructure that supports smooth configuration changes.
- Works on a variety of operating systems (Windows, MacOS, Linux, etc.) and supports all major cloud providers.
- Enables complete resource lifecycle management.
- Does not require any software on target systems.
- Exceptional at provisioning and managing cloud-based infrastructure (especially in multi-cloud environments).
- Has the backing of a large and active community.
Main cons of Terraform:
- No built-in GUI for any version of the tool.
- Tends to become challenging to manage when dealing with complex systems.
- Requires careful management of the Terraform State file (.tfstate) to avoid merge conflicts.
- Lack of error handling.
Terraform fully integrates with Bare Metal Cloud (BMC), our cloud-native dedicated server platform. It only takes a few lines of HCL code to deploy a brand-new BMC server (as demonstrated in our IaC with Terraform on BMC article).
Here's a list of Terraform's most notable features:
- A simple and concise language with a declarative syntax (the tool also supports an alternate JSON-compatible syntax).
- Enables users to edit, review, and version declarative configuration files through a command-line interface.
- An agentless architecture that does not require users to install additional software on target systems.
- Top-tier infrastructure provisioning and orchestration.
- State management that enables users to track infrastructure.
- Provisions immutable infrastructure, so the tool replaces the existing configuration with a new one whenever users make a change.
- A range of modules that speed up deployments.
- A plan-and-apply feature that previews changes without performing any updates.
- Graphs of all resources and dependencies.
- Drift detection that identifies problematic changes.
- Enables the use of custom plugins to extend the tool's functionality.
- Triggers from within most popular CI/CD pipelines (GitLab, Jenkins, Circle, etc.).
- Simplified rollbacks thanks to version-controlled configurations and managed states.
Learn how to provision infrastructure with Terraform and see to what extent this tool streamlines deployments.
How Does Terraform Work?
The first step in using Terraform is to define the desired infrastructure in HCL, the tool's native declarative language. You define all the resources (servers, networks, storage, load balancers, etc.) in a TF-config file, after which Terraform does two processes:
- Compare the current state of the infrastructure with the desired state described in the config file.
- Generate a plan on how to automatically reach the requested state on the node.
Unlike Ansible, writing Terraform configuration files does not require you to organize tasks in a specific sequence. You can also disperse code in multiple files if that approach makes more sense for your use case.
After creating a plan, the user previews the changes to the current infrastructure before applying an update. If the user approves, Terraform executes the configuration. If you are provisioning cloud computing resources, the tool communicates with the provider's API to create instances.
Once the tool deploys the desired resources, Terraform tracks the state of the infrastructure using a state file. This file records current resources and helps determine required changes on subsequent runs.
Terraform also provides detailed reporting of the infrastructure changes made during execution. The tool communicates any error or issue that occurred during provisioning to help users identify problems.
Check out our Terraform vs Puppet comparison to see how Terraform stacks up against one of Ansible's most notable competitors in configuration management.
Ansible vs Terraform: Comparison
The table below offers a detailed Ansible vs Terraform comparison:
|Point of comparison||Ansible||Terraform|
|Maintained by||Red Hat||HashiCorp|
|Initial release date||2012||2014|
|Primary focus||Configuration management and automation||Infrastructure provisioning and orchestration|
|Configuration language||HCL (HashiCorp Configuration Language)||YAML|
|Programming approach||A mix of declarative and procedural||Strictly declarative|
|Infrastructure mutability||Mutable infrastructure (i.e., updates components instead of replacing the whole infrastructure)||Immutable infrastructure (i.e., builds the entire system from scratch when you make a change)|
|Architecture||Master-less, communicates over SSH protocol||Master-less, communicates with providers using APIs|
|Packaging and templating||Complete support||Partial support|
|Push vs. pull||Both||Follows a push workflow|
|Built-in availability features||No||Yes|
|GUI support||No for the free version, yes for the enterprise edition||No official GUI (but there are third-party GUIs)|
|Community support||Large and active (somewhat lacking in terms of Windows support)||Large and active|
|Optimal use cases||Configuring preexisting systems and network automation||Provisioning infrastructure from scratch and managing cloud-based resources spread across multiple providers|
|Pricing||The basic version is free, the enterprise edition costs ~$10,000 per year for up to 100 nodes||The basic version is free, the enterprise edition charges custom prices based on usage|
Let's now take a closer look at the most notable differences between Ansible and Terraform.
Orchestration and Configuration Management
Ansible is primarily a configuration management tool, but it provides basic orchestration capabilities, such as:
- Running playbooks in parallel across multiple hosts.
- Performing rolling updates.
- Task control features (task retries, timeouts, error handling, etc.).
- A templating system that allows you to create dynamic configuration files.
On the other hand, Terraform provides far more features that enable users to orchestrate their infrastructure, such as managing complex dependencies between resources or managing multiple environments (development, staging, and production).
However, Terraform is not a full-blown configuration management tool. You can use Terraform to manage some aspects of configuration (e.g., set up security groups or configure load balancers), but the tool is not as flexible or powerful as Ansible.
Code: Declarative vs Procedural
Terraform users write declarative code in HCL to describe the desired state of the infrastructure. There's no need to detail how the tool should reach the desired state as users focus solely on the outcome instead of specific commands and steps.
The alternative to declarative coding is procedural (or imperative) programming in which you provide the program with a step-by-step guide to completing each task. Ansible is both declarative and procedural since:
- The tool uses YAML, which computers interpret and execute in a procedural manner (i.e., the exact sequence in which you write the code).
- Most Ansible modules work declaratively, so users do not have to specify exact steps for every task.
Ansible enables users to combine the two methodologies without having to adhere to a single paradigm. This mix offers more flexibility in terms of how you use the tool. On the other hand, Terraform's declarative approach is simpler and more intuitive, but you're limited to a certain way of defining resources.
Generally speaking, procedural languages are an excellent fit for system admins with a background in scripting. Declarative code is typically the preferred option for users with a programming background.
Ease of Use
Ansible is relatively easy to set up and use since:
- The tool is agentless, so you do not have to install any software on target devices.
- YAML-based playbooks are easy to write and read.
- The tool offers a range of pre-built modules that speed up operations.
Ansible tends to become more complex to use as your infrastructure grows. Large playbooks and complex dependencies are difficult to manage, especially for users with less experience in scripting.
Terraform is also relatively easy to set up and use due to simple-to-read HCL and a variety of pre-built modules. However, installing Terraform requires more upfront configuration and setup than Ansible as it requires the creation of a state file and some backend configuration.
Ansible primarily works with mutable infrastructure (an environment that changes after the initial installation). When a user updates the configuration, the tool tweaks the existing infrastructure to reach the desired state.
Terraform relies solely on immutable infrastructure. The tool never modifies servers after deployment and instead provisions a completely new set of infrastructure whenever the user makes a change. Meanwhile, the tool tears down the older set.
Ansible also supports some immutable infrastructure use cases, primarily through VM image creations and the tool's support for configuring container-based environments.
Ansible does not have built-in features for ensuring the availability of resources other than automating the failover process in the event of a server or service failure.
On the other hand, Terraform has various features for ensuring high availability, such as:
- Deploying resources to multiple cloud providers or availability zones.
- Storing states in a remote backend to improve fault tolerance.
- Creating auto-scaling groups that allow resources to scale automatically based on demand.
Learn about high availability (HA) and see how organizations minimize the likelihood of service downtime.
Ansible vs Terraform for Provisioning
Ansible is first and foremost a configuration management tool, but it also has some provisioning capabilities. The tool enables users to provision resources both in the cloud and on-prem (physical servers, virtual machines, containers, etc.).
Ansible also provisions apps and services, plus has a helpful templating feature that enables users to generate config files dynamically based on variables. However, the tool lacks a notion of state and does not track dependencies, so there's no lifecycle management for provisioned resources.
Terraform is primarily a provisioning tool, so it unsurprisingly offers excellent provisioning capabilities. The tool enables users to:
- Provision resources across multiple cloud providers and on-prem infrastructure.
- Use various pre-built modules for deploying from popular cloud providers.
- Rely on a state management system that tracks the state of resources over time and rolls back changes when necessary.
- Preview deployments with the plan-and-apply feature.
- Use templating to generate configuration files dynamically.
If you're looking for a long-term provisioning tool, Terraform is far more flexible and manageable than Ansible. Terraform is also the better option when provisioning cloud-based resources.
Ansible or Terraform: How to Choose
Choosing between Ansible and Terraform comes down to your IT priorities. Ansible is the better option when you're:
- On the market for a configuration management and multi-purpose automation tool.
- In the habit of regularly configuring preexisting resources.
- Looking to automate a variety of configuration-related tasks.
- Relying on a team that prefers working with YAML or has hands-on experience with Ansible.
On the other hand, Terraform is the better choice when you're:
- On the market for an infrastructure provisioning and management tool.
- Running most of your infrastructure in the cloud.
- Planning to build infrastructure from scratch.
- Looking for an IaC tool with built-in state management and availability features.
- Relying on a team that has hands-on experience with Terraform.
Since the two tools complement each other, there are situations in which you should use both Ansible and Terraform. For example, let's say you must provision a Bare Metal Cloud instance with a MySQL server configured with a variety of:
- Port settings.
- Security constraints.
- Performance optimization parameters.
In that scenario, it's a sensible decision to use Terraform to provision the BMC server via the Bare Metal Cloud API and then use Ansible to set up and configure the MySQL database.
Making the most out of Terraform or Ansible requires a high level of DevOps maturity. Check your DevOps maturity level and see whether your team is ready to take on one (or both) of these tools.
Two Complementary, Not Competitive Tools
Ansible and Terraform have their fair share of similarities, but the two tools have distinct purposes. Just because you can create resources with Ansible doesn't necessarily mean that's a good long-term solution. Likewise, Terraform is not ideal for in-depth configuration management, so ensure your team has a sound understanding of go-to use cases for both of these powerful tools.