DEV Community

Anurag Vishwakarma for firstfinger

Posted on • Originally published at firstfinger.in on

Ansible vs Terraform

Ansible vs Terraform

Imagine, As your business grows bigger, setting up and configuring things like servers, databases, and networks becomes a real pain if you do it by hand. Spinning up new servers one by one, copying and pasting commands, and keeping track of everything is super time-consuming and mistakes happen easily. Keeping all your servers configured the same way, installing updates, and deploying new code versions is a nightmare without help.

That's where tools like Terraform and Ansible come to the rescue. Terraform is awesome at setting up your infrastructure like servers, networks, and databases. Instead of doing everything manually, you write code that describes what you want, and Terraform handles it for you. Need 10 new servers? Terraform gets it done with just a few commands.

Ansible is the superhero for configuring those servers. You create instructions called playbooks that tell Ansible how to set up each server. Install software? Check. Deploy your code? Check. Update everything? Easy peasy. Ansible makes sure all your servers are configured consistently.

But it gets even better! With Terraform and Ansible, you have your entire infrastructure and configurations defined as code. This makes it super easy to see what changed, roll back to an earlier version if needed, and prove you're following regulations.

💡 IaC : Infrastructure as Code.

6 Reasons: Why Do We Need Infrastructure Automation and Configuration Management (IaC) Tools?

  1. Eliminating Manual Errors
  2. Increasing Speed and Efficiency
  3. Ensuring Consistency and Standardization
  4. Improving Security and Compliance
  5. Facilitating Collaboration and Version Control
  6. Simplifying Disaster Recovery and Rollbacks

Infrastructure automation refers to the process of using software tools and scripts to automate the provisioning, configuration, and management of IT infrastructure resources, such as virtual machines, networks, load balancers, and storage systems.

Configuration management is the practice of maintaining the desired state and configuration of IT systems and services throughout their lifecycle. It involves tracking, managing, and updating the configuration items (CIs) that make up an IT system, such as software, hardware, and network devices.


Terraform: The Infrastructure Provisioning Tool

Terraform is a declarative infrastructure provisioning tool that shines when it comes to spinning up resources across multiple cloud providers.

Terraform's strengths lie in:

1. Declarative Approach

Terraform's declarative nature means you define your desired infrastructure state, and it figures out the necessary steps to achieve that state. This approach simplifies complex provisioning scenarios and ensures consistent, repeatable deployments.

2. State Management and Lifecycle Management

Terraform maintains a state file that tracks the resources it has provisioned. This state file enables seamless lifecycle management, allowing you to modify or delete resources without manual intervention. If you remove a resource from your configuration, Terraform will automatically delete it during the next application.

3. Idempotency

Terraform is idempotent, meaning you can run it multiple times without unintended changes to your infrastructure. If no changes are required, Terraform won't perform any actions, saving you time and effort.


Ansible: The Configuration Management Tool

Ansible is a powerful configuration management tool that excels at automating application deployments, system configurations, and ongoing maintenance tasks.

Ansible strengths are:

1. Hybrid Approach

Ansible combines declarative resources with procedural execution, providing a flexible approach to configuration management. While resources are defined in a declarative manner, they are executed procedurally.

2. Application Deployment

Ansible simplifies the process of deploying applications by automating tasks like installing dependencies, copying files, and starting services.

3. Agentless

Unlike some other configuration management tools, Ansible doesn't require an agent to be installed on the managed nodes. This agentless architecture makes it easy to manage diverse environments without additional overhead.


Ansible vs Terraform

Ansible vs Terraform

Category Ansible Terraform
Primary Focus Configuration management, application deployment, orchestration Infrastructure as Code (IaC)
Language YAML (Playbooks) HCL (Configuration files)
Agent Agentless (connects via SSH) Agent-based (Terraform agent)
Resource Management Manages existing resources Creates and manages resources
Change Handling Idempotent; handles changes in config Versioning and drift detection
Providers Limited to supported modules Extensive list of providers
Cloud Support Good cloud support Excellent cloud support
Use Cases Application Deployment, Configuration Management, Orchestration Infrastructure Provisioning, Resource Management

Using Terraform and Ansible Together

While Terraform and Ansible have distinct strengths, they can work together seamlessly to provide a complete infrastructure automation solution.

Ansible vs Terraform

Here are two common approaches:

First Approach: Start with Terraform for Provisioning, then Use Ansible for Configuration Management

In this approach, you begin by defining your infrastructure resources using Terraform. Once the provisioning is complete, you can invoke Ansible from within your Terraform configuration to handle configuration management tasks on the newly created resources.

# Terraform configuration
resource "aws_instance" "web_server" {
  # ... instance details ...

  provisioner "local-exec" {
    command = "ansible-playbook -i '${aws_instance.web_server.public_ip},' playbook.yml"
  }
}
Enter fullscreen mode Exit fullscreen mode

Second Approach: Start with Ansible and Call Terraform for Initial Provisioning

Alternatively, you can start with an Ansible playbook and call Terraform from within it to handle the initial infrastructure provisioning. Once the resources are ready, Ansible can take over and manage their configuration.

# Ansible playbook
- hosts: localhost
  tasks:
    - name: Provision infrastructure with Terraform
      terraform:
        project_path: '/path/to/terraform/project'
        state: present

    - name: Configure provisioned resources
      # ... configuration management tasks ...
Enter fullscreen mode Exit fullscreen mode

Example: Setting up a Jenkins Environment Using Terraform and Ansible

Now, let's put our knowledge into action by setting up a Jenkins environment using Terraform and Ansible.

1. Terraform for Provisioning an EC2 Instance on AWS

provider "aws" {
  region = var.region
}

resource "aws_vpc" "main" {
  # ... VPC configuration ...
}

resource "aws_instance" "jenkins" {
  ami = data.aws_ami.ubuntu.id
  instance_type = var.instance_type
  # ... other instance details ...
}
Enter fullscreen mode Exit fullscreen mode

main.tf

variable "region" {
  default = "us-east-1"
}

variable "instance_type" {
  default = "t2.micro"
}
Enter fullscreen mode Exit fullscreen mode

variables.tf

How to Create & Deploy EC2 Instance Using Terraform?

2. Ansible for Deploying Docker and Running Jenkins Container

Once the EC2 instance is provisioned, Ansible takes over to deploy Docker and run the Jenkins container.

Here's what the Ansible playbook looks like:

- hosts: jenkins_hosts
  become: yes
  tasks:
    - name: Install prerequisites
      apt:
        name:
          - apt-transport-https
          - ca-certificates
          - curl
          - software-properties-common
        state: latest

    - name: Add Docker GPG key
      apt_key:
        url: https://download.docker.com/linux/ubuntu/gpg
        state: present

    # ... additional tasks to install Docker ...

    - name: Pull Jenkins Docker image
      docker_image:
        name: jenkins/jenkins:lts
        source: pull

    - name: Run Jenkins container
      docker_container:
        name: jenkins
        image: jenkins/jenkins:lts
        ports:
          - "8080:8080"
Enter fullscreen mode Exit fullscreen mode

playbook.yml

We start by defining our infrastructure resources using Terraform. Then, we run terraform apply to provision the required resources. Once the infrastructure is provisioned, we invoke an Ansible playbook to configure and manage the resources as needed.

Terraform and Ansible are not competitors; they are complementary tools that, when used together, can unlock the full potential of infrastructure automation.

Top comments (0)