-

Ansible and Terraform

Infrastructure as Code (IaC)

Servers, networks, and other resources are defined using configuration files:

Benefits:

  • automation
  • repeatability
  • versioning (e.g., via Git)
  • reduced risk of errors

Ansible and Terraform

Tools for allocating and managing resources using configuration files.

Ansible

an open-source tool for automating server configuration and management. It allows you to define the desired system state and ensure its achievement.

  • does not use background monitoring processes (agents).
  • simple YAML notation

Ansible Architecture

  • Controller – the computer from which we run Ansible
  • Managed Nodes – target servers

Key Components

  • Inventory – list of servers
  • Playbook – task definition file
  • Modules – perform specific operations (e.g. install a package)

Ansible Playbook Example

- name: Install and start nginx
hosts: web
become: true

tasks:
- name: Install nginx
apt:
name: nginx
state: present

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

Explanation:

  • hosts: which servers to run on
  • tasks: list of tasks
  • apt: package management module
  • service: service management module

Terraform

What is Terraform

a tool from HashiCorp for infrastructure management using declarative language (HCL).

It is mainly used for:

  • building cloud infrastructure (AWS, Azure, GCP)
  • managing resources (VMs, networks, databases)

Basic principles

Declarative approach

We define what we want, not how to get it.

State

Terraform stores the current state of the infrastructure in a file:

terraform.tfstate

Workflow

  1. init – initialize the project
  2. plan – preview changes
  3. apply – commit changes
  4. destroy – remove infrastructure

Terraform configuration example

provider "aws" {
region = "eu-central-1"
}

resource "aws_instance" "web" {
ami = "ami-123456"
instance_type = "t2.micro"

tags = {
Name = "web-server"
}
}

Explanation:

  • provider – cloud provider
  • resource – resource definition (virtual server)
  • ami – system image
  • instance_type – type instances

Ansible vs Terraform Comparison

Feature Ansible Terraform
Usage server configuration resource allocation
Access imperative declarative
Language YAML HCL
Agent no no

Summary

  • Ansible is used to configure and manage servers

  • Terraform is used to build infrastructure

  • Together they form a powerful combination in DevOps:

  • Terraform builds the infrastructure

  • Ansible configures it

Reload?