DevOps
Infrastructure as Code
Introduction to Ansible

Introduction to Ansible

Ansible is an open-source automation tool that simplifies the way you manage servers, deploy applications, and orchestrate complex IT tasks. It is industry-renowned for its simplicity and human-readable configuration.


⚡ The Agentless Advantage

Unlike many other automation tools (like Chef or Puppet), Ansible is Agentless.

  • How it works: Ansible connects to managed nodes via standard SSH (for Linux) or WinRM (for Windows).
  • Benefits: No extra software to install or maintain on the servers you are managing. This reduces security overhead and simplifies bootstrapping.

🏗️ Ansible Architecture

  • Control Node: The machine where Ansible is installed and where you run the commands.
  • Managed Nodes: The remote servers (hosts) that Ansible manages.
  • Inventory: A simple file (usually INI or YAML) that lists the IP addresses or hostnames of your managed nodes.
  • Modules: Small programs that Ansible pushes to the nodes to execute specific tasks (e.g., apt, service, copy).

📖 YAML Playbooks

Playbooks are the heart of Ansible. They are written in YAML, making them extremely easy for both developers and operations teams to read and write.

---
- name: Install and Start Nginx
  hosts: webservers
  become: yes  # Run as sudo
  
  tasks:
    - name: Ensure Nginx is installed
      apt:
        name: nginx
        state: latest
        
    - name: Ensure Nginx is started
      service:
        name: nginx
        state: started
        enabled: yes

Key Components:

  • hosts: Specifies which group of servers from your inventory to target.
  • become: Tells Ansible to escalate privileges (similar to sudo).
  • tasks: A list of actions to perform in sequential order.

🔁 The Power of Idempotency

One of Ansible's greatest strengths is Idempotency.

If you run a playbook that says "Ensure Nginx is installed," and Nginx is already there, Ansible will do nothing. This allows you to run the same playbooks repeatedly to ensure your system is in the desired state without risking accidental changes or errors.


[!TIP] Ad-Hoc Commands For quick tasks, you don't even need a playbook! You can run ad-hoc commands like: ansible all -m ping (To check connectivity) ansible webservers -m reboot (To reboot a group of servers)