Skip to content
SumGuy's Ramblings
Go back

Ansible vs. Terraform: Cloud Infrastructure Management

In the evolving landscape of DevOps and Infrastructure as Code (IaC), two significant tools have emerged as front-runners for managing large-scale IT infrastructure: Ansible and Terraform. Both tools aim to automate and simplify infrastructure management, but they do so in distinct ways that cater to different aspects of IT operations. This comprehensive guide will explore Ansible and Terraform, their similarities, differences, and how to choose the right tool based on your operational needs.

What is Ansible?

Ansible, managed by Red Hat, is an open-source automation tool or platform used for IT tasks such as configuration management, application deployment, intra-service orchestration, and provisioning. Interestingly, Ansible operates on an agentless architecture, relying on SSH and Python to manage nodes, which makes it simple and easy to set up and use.

What is Terraform?

Terraform, on the other hand, is an open-source IaC tool created by HashiCorp that allows users to define and provision data center infrastructure using a declarative configuration language known as HashiCorp Configuration Language (HCL). Unlike Ansible, Terraform is designed to handle the service life cycle from the ground up, specializing in infrastructure management.

Similarities between Ansible and Terraform

Despite their different approaches, Ansible and Terraform share a few similarities:

Key Differences between Ansible and Terraform

The primary differences between Ansible and Terraform lie in their design philosophy and operational focus:

Choosing Between Ansible and Terraform

The choice between Ansible and Terraform can be dictated by specific project requirements:

Ansible: Pros and Cons

Pros:

Cons:

Terraform: Pros and Cons

Pros:

Cons:

Both Ansible and Terraform excel in their respective domains. Choosing between them—or deciding to use them together—depends on the specific needs of the project or organization, such as the scale of operations, type of infrastructure involved, and the desired workflows for deploying and maintaining that infrastructure. It’s often beneficial to leverage their strengths in tandem to cover all aspects of infrastructure and application management lifecycle efficiently.

Let’s consider a common task: creating an AWS EC2 instance, which is a quintessential piece of infrastructure used in many projects. Below, I provide sample code for achieving this in both Ansible and Terraform. This example will help illustrate how each tool manages this task.

Terraform Code

provider "aws" {
  region = "us-east-1"
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  tags = {
    Name = "ExampleInstance"
  }
}

Explanation

In this Terraform script, when executed, Terraform will ensure that an AWS EC2 instance exactly matching this description exists. If it doesn’t, Terraform will create it. If the script is updated, Terraform will apply the changes accordingly.

Ansible Code

---
- hosts: localhost
  gather_facts: no
  tasks:
    - name: Create a new EC2 instance
      amazon.aws.ec2_instance:
        name: ExampleInstance
        region: us-east-1
        image_id: ami-0c55b159cbfafe1f0
        instance_type: t2.micro
        wait: yes
        wait_timeout: 600
        tags:
          Name: ExampleInstance
      register: ec2

Explanation

In this Ansible playbook, executing it will create an EC2 instance with the specified parameters. Unlike Terraform, Ansible does not track the state of the system. Each run of the playbook will attempt to ensure the desired state declared in the tasks but without the awareness of the actual current state unless explicitly checked. Based on this example Terraform is ideal for provisioning and managing the lifecycle of concrete infrastructure components using a declarative approach. Ansible, being more oriented towards configuration management and application deployment, excels in mutable environments where you need to enforce a certain state without necessarily rebuilding infrastructure from scratch. In practice, these tools can often complement each other in a DevOps environment—Terraform to set up and manage the infrastructure, and Ansible for the configuration and application layers.

Let’s look at another common scenario in infrastructure management: creating a secure Virtual Private Cloud (VPC) on AWS. This example will showcase how both Ansible and Terraform can be used to establish this key piece of network infrastructure.

Terraform Code

provider "aws" {
  region = "us-east-1"
}

resource "aws_vpc" "example_vpc" {
  cidr_block           = "10.0.0.0/16"
  enable_dns_support   = true
  enable_dns_hostnames = true
  tags = {
    Name = "ExampleVPC"
  }
}

resource "aws_internet_gateway" "example_gateway" {
  vpc_id = aws_vpc.example_vpc.id
  tags = {
    Name = "ExampleGateway"
  }
}

Explanation

This script, when applied, will ensure the creation of a VPC with an internet gateway configured as specified. The use of Terraform’s state allows for tracking these resources over time.

Ansible Code

- hosts: localhost
  gather_facts: no
  tasks:
  - name: Create a VPC
    amazon.aws.ec2_vpc_net:
      name: ExampleVPC
      cidr_block: 10.0.0.0/16
      region: us-east-1
      dns_support: true
      dns_hostnames: true
      state: present
    register: vpc

  - name: Create an Internet Gateway
    amazon.aws.ec2_vpc_igw:
      vpc_id: "{{ vpc.vpc.id }}"
      region: us-east-1
      state: present
      tags:
        Name: ExampleGateway

Explanation Playbook Setup: Declares localhost and disables fact gathering. Tasks: Create a VPC: Uses ec2_vpc_net to define a VPC with similar parameters to the Terraform example. The state is set to ‘present,’ which ensures the VPC exists as defined. Create an Internet Gateway: Utilizes ec2_vpc_igw to attach an internet gateway to the VPC. The VPC ID is dynamically pulled from the previous task using Ansible’s registering mechanism to hold state across tasks within the playbook. Here, executing this playbook will create the specified VPC and internet gateway on AWS. Ansible’s approach involves imperative tasks that adjust the infrastructure to match the desired state without an ongoing tracking mechanism. Each task must be idempotent to avoid creating duplicate resources on repeat runs. Terraform is very effective when you need to ensure entire environments are managed with clear, trackable configurations, all defined upfront. It shines in scenarios where infrastructure setup and lifecycle management are complex and tightly controlled. Ansible is great for operations or environments where configurations might change dynamically and frequently, and where the management includes not just the deployment but also the ongoing operation and orchestration of various components. Using the example of setting up a VPC, both tools once again demonstrate strengths in their respective areas of provisioning and configuration, guiding decisions based on project specifics, infrastructure requirements, and team capabilities.

Let’s demonstrate how both Ansible and Terraform can be used to manage resources on Google Cloud Platform (GCP). In this scenario, we’ll create a Google Cloud Storage bucket, which is a fundamental and widely used service for storing any amount of data.

Terraform Code Below is a Terraform script to create a Google Cloud Storage bucket.

provider "google" {
  credentials = file("<CREDENTIALS_JSON_FILE>")
  project     = "<YOUR_PROJECT_ID>"
  region      = "us-central1"
}

resource "google_storage_bucket" "example_bucket" {
  name     = "my-unique-bucket-name"
  location = "US"
  
  storage_class = "STANDARD"

  lifecycle_rule {
    condition {
      age = 10
    }
    action {
      type = "Delete"
    }
  }

  versioning {
    enabled = true
  }
}

Explanation

With this Terraform script, when executed, Terraform will ensure the existence of a Google Cloud Storage bucket with these exact specifications, managing it throughout its lifecycle.

Ansible Code

Here is an Ansible playbook to achieve the same objective.

---
- hosts: localhost
  gather_facts: no
  tasks:
    - name: Create GCP Storage Bucket
      google.cloud.gcp_storage_bucket:
        name: "my-unique-bucket-name"
        project: "<YOUR_PROJECT_ID>"
        auth_kind: serviceaccount
        service_account_file: "<CREDENTIALS_JSON_FILE>"
        location: "US"
        storage_class: "STANDARD"
        state: present
        versioning:
          enabled: true
      register: gcp_bucket

Explanation

Executing this playbook will ensure the creation or configuration of the specified Google Cloud Storage bucket as per the parameters. Unlike Terraform, Ansible does not keep a state of the infrastructure but ensures the desired state during each execution.

Both Terraform and Ansible demonstrate robust capabilities in managing cloud resources like storage buckets in GCP, albeit from slightly different operational paradigms:

Choosing between them (or deciding to use them in conjunction) depends on factors like existing workflows, team familiarity with the tools, and specific project requirements.


Share this post on:

Previous Post
Tmux for Streamlining Dev Workflow
Next Post
WordPress, Docker, NGINX, and MySQL via Ansible