DevOps

Ansible vs Terraform: Best DevOps tool?

Compare Ansible vs Terraform, focusing on configuration management, infrastructure provisioning, cloud deployment, automation, differences

Ansible and Terraform are excellent DevOps tools that can provide many automation benefits in enterprise and cloud environments. Both of them have capabilities that can overlap with each other. However, I would say that each has its strengths in configuring and provisioning infrastructure. Look at Ansible vs Terraform and see which automation tool is best for which task.

At a high-level

Ansible and Terraform are two of my favorite DevOps tools as they provide quick time to value, and you can start accomplishing a lot by using them. I started first with Ansible as for me I was looking more for a configuration management tool at the time.

When I started looking to provision infrastructure, Terraform was the name that kept coming up. And it is great at provisioning infrastructure. The short answer, in my opinion, to Ansible vs Terraform is this:

  • Ansible for configuration management

  • Terraform for infrastructure provisioning

I think these are the strength of these two DevOps tools. However, can they both do some configuration management and deploy infrastructure? Yes, they can. I think Ansible is probably better at playing both sides than Terraform. However, Terraform has provisioners that can be used for some configuration management, but this is not its strong suit, and the provisioned actions aren’t tracked in state management.

Ansible is an all-out jack of all trades that can do almost anything you want it to do, including spinning up infrastructure. However, I tend to use Terraform more in this realm than Ansible for configuration management and everything else.

Let’s look at each in a bit more detail.

Installing Ansible vs Terraform

The award for ease of “installation” definitely goes to Terraform. Terraform is a self-contained binary you download from Hashicorp. You are ready to rock and roll with Terraform as soon as you download the binary. Ansible is a bit more involved as you need to ensure you have Python and a few other things installed along with installing Ansible itself, especially if you are working with things like Kerberos in Windows environments.

Below is an example of installing related components and Ansible. You can pull it from most Linux repositories and also use it in Windows by installing it in Windows Subsystem for Linux (WSL). This is a noted difference between Ansible and Terraform. Terraform does have native Windows support without WSL. However, Ansible does require WSL to work on a Windows machine.

apt-get update && \
    apt-get install -y gcc python-dev libkrb5-dev && \
    apt-get install python3-pip -y && \
    pip3 install --upgrade pip && \
    pip3 install --upgrade virtualenv && \
    pip3 install pywinrm[kerberos] && \
    apt install krb5-user -y && \ 
    pip3 install pywinrm && \
    pip3 install ansible

Terraform is just a single binary file download from here: Install | Terraform | HashiCorp Developer. After downloading, you add a PATH variable to point to your Terraform binary.

Download and install the Terraform binary
Download and install the Terraform binary

Ansible for Configuration Management

With Ansible, configuration management is as straightforward as writing simple YAML configuration files. Ansible provides a comprehensive orchestration and configuration management solution and offers a wide range of automation tools for managing infrastructure resources, operating system configuration tasks, and much more.

Running Ansible from the command line
Running Ansible from the command line

Automation with Ansible

Ansible automates provisioning, configuration changes, and the deployment of applications on bare metal servers, virtual machines, and cloud platforms. Its ability to manage infrastructure extends to orchestrating and configuring network components and can even support bare metal provisioning.

Mutable vs. Immutable Infrastructure with Ansible

While Ansible’s approach to mutable infrastructure allows for flexibility in configuration management tasks, it can lead to challenges when configuration drift occurs. State management becomes crucial to ensure that the provisioned infrastructure aligns with the desired configurations.

Configuration Management in Depth

Understanding configuration management is crucial in modern IT environments. Between Ansible and Terraform, several nuances define their approach to configuration management. Let’s explore these areas further:

Ansible Configuration Management

Ansible’s configuration management is centered around its use of playbooks written in YAML. These playbooks allow users to define the desired state of their infrastructure components, making them easy to read and write. Here’s an example of an Ansible playbook that sets up a web server:

---
- name: Set up Apache web server
  hosts: webservers
  tasks:
    - name: Ensure Apache is installed
      package:
        name: httpd
        state: present
    - name: Start Apache
      service:
        name: httpd
        state: started

Mutable Infrastructure Approach

Ansible supports changes to existing infrastructure, allowing for modifications to be made on-the-fly. This approach enables incremental changes, and thus, can provide greater flexibility in managing infrastructure resources.

Ansible’s extensive collection of modules and plugins allow users to perform a wide array of configuration management tasks. From managing infrastructure to operating system configuration tasks, Ansible has the ability to handle them all.

Terraform Configuration Management

Terraform employs HashiCorp Configuration Language (HCL), specifically designed to describe infrastructure resources. It provides a concise way to define the desired state of infrastructure. Here’s an example of a Terraform code snippet to create a cloud instance:

resource "aws_instance" "example" {
  ami           = "ami-0c94855ba95c71c99"
  instance_type = "t2.micro"
}
Running Terraform from the command line
Running Terraform from the command line

Immutable Infrastructure and State management

Terraform focuses on immutable infrastructure, where changes are made by replacing existing infrastructure rather than modifying it. This ensures a robust infrastructure management process and minimizes risks, such as configuration drift, where unintended changes may occur.

Terraform emphasizes state management by keeping a record of the existing infrastructure and its configuration. This helps synchronize the real-world infrastructure with the code and allows for predictable changes.

Cloud Provisioning and Multiple Providers

Terraform excels in provisioning infrastructure across multiple cloud platforms. Its support for multiple providers ensures that the same configuration can be applied across different cloud environments.

Initializing Terraform cloud providers
Initializing Terraform cloud providers

Infrastructure Automation and Provisioning

Both Ansible and Terraform are renowned for their infrastructure automation capabilities. Here’s how they handle these tasks to create infrastructure.

Ansible for Infrastructure Automation

With the Ansible automation platform, you can automate a wide range of tasks. These tasks include configuring servers, managing cloud services, etc. For example, here’s a snippet of Ansible code that installs Nginx on a web server and starts the service:

- name: Install Nginx
  apt:
    name: nginx
    state: present
  notify:
    - Start Nginx

handlers:
  - name: Start Nginx
    service:
      name: nginx
      state: started

Terraform for Infrastructure Provisioning

Terraform specializes in provisioning infrastructure across various cloud platforms. It enables precise control over cloud provisioning by using its infrastructure as code approach. For instance, here’s how you can create a Virtual Private Cloud (VPC) in AWS using Terraform:

resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
}

Terraform’s compatibility with multiple providers ensures that the same provisioning code can be utilized across various cloud platforms such as AWS, Azure, and Google Cloud. This facilitates a multi-cloud deployment strategy.

Terraform and Ansible for Network Automation

Ansible uses playbooks and modules specifically designed for network automation, allowing for the configuration of switches, routers, and other network devices. Here’s an example of configuring a VLAN on a Cisco switch using Ansible:

---
- name: Configure VLAN 100
  hosts: cisco_switch
  tasks:
    - name: Ensure VLAN 100 exists
      ios_vlan:
        vlan_id: 100
        name: My_VLAN
        state: present

This YAML code connects to the Cisco switch specified under “cisco_switch” and ensures that VLAN 100 is configured with the given name.

Key Features:

  • Device-Specific Modules: Ansible has device-specific modules for various vendors, simplifying the configuration tasks.

  • Integration with Existing Infrastructure: Ansible can manage configurations seamlessly with the existing network infrastructure.

  • Mutable Infrastructure: Ansible can make direct changes to the current configuration, supporting a mutable infrastructure approach.

Terraform Network Automation

Terraform also offers network automation capabilities but takes a different, declarative approach. Here’s an example of creating a VPC and subnet in AWS using Terraform:

resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
}

resource "aws_subnet" "subnet" {
  vpc_id     = aws_vpc.main.id
  cidr_block = "10.0.1.0/24"
}

This HCL code sets up a VPC and a subnet within it in AWS, following the specified CIDR blocks.

Key Features:

  • Declarative Syntax: Terraform uses HashiCorp Configuration Language (HCL), offering a declarative syntax that describes the desired state.

  • Immutable Infrastructure Approach: Terraform’s approach ensures that changes are made by creating new resources, avoiding configuration drift.

  • Provider Support: Terraform supports multiple providers, enabling consistent code across various cloud platforms and network services.

Building Cloud Infrastructure: Ansible vs. Terraform

Let’s consider examples between the two of creating cloud infrastructure.

Ansible for Cloud Infrastructure

Ansible uses playbooks to define the desired state of cloud resources. Here’s an example of creating an EC2 instance in AWS using Ansible:

- name: Launch an EC2 instance
  hosts: localhost
  tasks:
    - name: Create EC2 instance
      ec2:
        key_name: mykey
        instance_type: t2.micro
        image: ami-12345678
        wait: yes
        group: webserver

This code snippet ensures the creation of an EC2 instance in the specified security group with the given key and instance type.

Key Aspects of Ansible:

  • Integration with Cloud Services: Ansible has modules for various cloud services, allowing for seamless integration.

  • Flexible Configuration Management: Ansible’s YAML-based configuration files are human-readable and support reusable roles.

  • Mutable Infrastructure Approach: Ansible makes adjustments to existing infrastructure resources, enabling quick configuration changes.

Terraform for Cloud Infrastructure

Terraform uses declarative HCL to manage cloud resources. Here’s an example of defining an AWS EC2 instance using Terraform:

resource "aws_instance" "my_instance" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"
  key_name      = "mykey"
  vpc_security_group_ids = ["webserver"]
}

This code ensures that the EC2 instance exists with the specified attributes.

Key Aspects of Terraform:

  • Declarative Syntax: Terraform describes the desired state of infrastructure, creating or modifying resources accordingly.

  • Immutable Infrastructure: Terraform provisions new resources for changes, minimizing the risks of configuration drift.

  • Provider Support: Terraform’s wide range of providers allows for a consistent approach across different cloud platforms.

Deploying Across Multiple Cloud Platforms

Terraform for Multi-Cloud Deployment

Terraform can handle deployments across multiple cloud platforms from its extensive provider support. Here’s an example of creating a virtual machine in Azure:

resource "azurerm_virtual_machine" "my_vm" {
  name                  = "myvm"
  location              = "East US"
  resource_group_name   = "myResourceGroup"
  vm_size               = "Standard_DS1_v2"
}

This code creates a VM in Azure using the specified parameters.

Ansible for Multi-Cloud Management

Ansible can also manage infrastructure across various clouds through its cloud-specific modules. Here’s an example of creating a Google Compute Engine instance:

- name: Create instance(s) on GCE
  gce:
      instance_names: my-instance
      machine_type: n1-standard-1
      image: debian-11

This playbook ensures the creation of an instance in GCE with the given specifications.

Comparison of Key Differences

The key differences between Ansible and Terraform come down to their core functionalities and how they approach common tasks:

Ansible Terraform Approach to Cloud Services

While both can manage cloud services, Ansible offers broader configuration management tools, whereas Terraform specializes in cloud provisioning. Understanding these nuances is essential when choosing the right tool for your specific cloud infrastructure needs.

Infrastructure Management: An In-Depth Look

Infrastructure management involves a complex set of tasks. Both Ansible and Terraform provide extensive capabilities, but their approach differs in managing infrastructure resources, handling network automation, and integrating with various network devices.

Versioned Software Component Installation

Ansible excels in tasks like versioned software component installation and managing configurations across various infrastructure components. While strong in provisioning infrastructure, Terraform may require additional tools for detailed configuration management tasks.

Code Examples: Ansible vs. Terraform

Comparing running code between Ansible and Terraform can provide valuable insights into their operation. Here are examples for both:

Ansible Code Example

- name: Install Apache
  hosts: webservers
  tasks:
    - name: Install httpd
      yum:
        name: httpd
        state: present

Terraform Code Example

provider "aws" {
  region = "us-west-2"
}

resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

output "ip" {
  value = aws_instance.web.public_ip
}

These examples illustrate how Ansible focuses on managing configurations and Terraform on provisioning infrastructure.

Frequently Asked Questions

How does Ansible compare to Terraform in treating infrastructure as code?

Treating infrastructure as code is a common approach in modern infrastructure management. While Ansible playbook focuses on automating operating system configuration tasks and software defined networking, Terraform uses a more declarative infrastructure approach, allowing for easier state management and provisioned infrastructure consistency.

Can Terraform and Ansible work together, and how?

Yes, Terraform and Ansible can be integrated to manage infrastructure, with Terraform handling the provisioning and Ansible automating the configuration. This combines the benefits of immutable infrastructure with versatile configuration management capabilities. You can use Terraform to provision infrastructure and then leverage Ansible to manage the newly provisioned resources, including web servers and network components.

How do Ansible and Terraform support bare metal provisioning?

Both tools offer support for bare metal provisioning, although their approaches differ. Ansible provides direct support for configuring servers and managing network devices, making it suitable for handling bare metal servers. On the other hand, Terraform focuses on provisions infrastructure across different platforms, including bare metal, through its various providers.

What are the key considerations for choosing between Terraform vs Ansible for cloud provisioning?

Regarding cloud provisioning, the choice between Terraform vs Ansible depends on various factors. Terraform’s cloud deployment capabilities and support for multiple cloud platforms make it ideal for provisioning new cloud infrastructure. Ansible’s strength lies in its flexibility to manage cloud services and configure existing infrastructure, allowing for seamless integration with various cloud platforms and automation controllers.

What is the significance of lifecycle management in Ansible and Terraform?

Lifecycle management plays a critical role in both tools. Ansible’s automation solution includes managing lifecycle aspects like application deployment, configuration changes, and external resource management. Terraform’s focus on immutable infrastructure ensures that the infrastructure components’ lifecycle remains consistent, reducing the risk of unexpected changes.

Wrapping up: Ansible and Terraform in Modern IT

The answer no one ever likes: the choice between Ansible and Terraform depends on specific needs and preferences. These two tools provide powerful capabilities, from managing infrastructure resources to deploying applications and provisioning new cloud infrastructure.

Understanding their key differences, such as mutable vs. immutable infrastructure, configuration management capabilities, and how they approach tasks like provisioning infrastructure or configuring servers, helps you find the right tool for your needs.

In my opinion, there is never “one” tool that can do everything you want everywhere. Using both Ansible and Terraform together allows you to have the best of both worlds.

Subscribe to VirtualizationHowto via Email 🔔

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Brandon Lee

Brandon Lee is the Senior Writer, Engineer and owner at Virtualizationhowto.com and has over two decades of experience in Information Technology. Having worked for numerous Fortune 500 companies as well as in various industries, Brandon has extensive experience in various IT segments and is a strong advocate for open source technologies. Brandon holds many industry certifications, loves the outdoors and spending time with family.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.