The Complete Ansible Tutorial: Concepts, Architecture, Playbooks, and Real-World Examples

DevOps

MOTOSHARE 🚗🏍️
Turning Idle Vehicles into Shared Rides & Earnings

From Idle to Income. From Parked to Purpose.
Earn by Sharing, Ride by Renting.
Where Owners Earn, Riders Move.
Owners Earn. Riders Move. Motoshare Connects.

With Motoshare, every parked vehicle finds a purpose. Owners earn. Renters ride.
🚀 Everyone wins.

Start Your Journey with Motoshare

Ansible: A Comprehensive Tutorial

Introduction to Ansible

Ansible is an open-source automation tool used for configuration management, server management, and application deployment. Developed by Red Hat, it is written in Python and is known for its simplicity, agentless architecture, and powerful automation capabilities.

Key Terminology

  • Configuration Management Tool: Software that automates the setup, configuration, and maintenance of systems.
  • Server Management Tool: A tool that helps administrators manage servers, including installing software, updating configurations, and monitoring services.
  • Deployment Tool: Automates the process of delivering applications or updates to multiple servers.

Ansible Editions

EditionInterfaceLicensingDescription
AnsibleCLIFreeCommand-line interface for automation tasks.
TowerUIPaidEnterprise-grade web UI for Ansible.
AWXUIFreeOpen-source version of Ansible Tower.

Why Use Ansible?

Organizations use Ansible to automate repetitive tasks, manage large numbers of servers, and ensure consistency across environments.

Benefits

  • Cost Savings: Automate changes across hundreds of servers, reducing manual effort.
  • Time Savings: Execute tasks simultaneously on multiple systems.
  • Quality Improvement: Ensure consistent changes and reduce human error.

Use Cases

  • IT Operations: Deploy system software, antivirus, policies, and more.
  • Development: Deploy applications and manage development environments.
  • Resource Management: Automate changes to files, directories, packages, services, users, and groups.

Ansible vs. Other Tools

Ansible is often compared to similar tools:

ToolLanguageAgentlessNotable Features
AnsiblePythonYesSimple YAML syntax, SSH-based
ChefRubyNoChef server/agent model
PuppetRubyNoDeclarative language, agent-based
CFEngineCNoLightweight, policy-based
SaltStackPythonYesEvent-driven automation

How Ansible Works

Architecture

  • ACS (Ansible Control Server): The machine where Ansible is installed and from which commands are issued.
  • ARS (Ansible Remote Server): Target machines managed by Ansible.

Workflow:

textHUMAN → ACS (Control Server) → ARS (Remote Servers)

Platform Support

  • Control Server: Typically Linux (64-bit), requires Python.
  • Remote Server:
    • Linux: Requires Python, communicates via SSH.
    • Windows: Requires PowerShell 3.0+ (.NET 4.5+), communicates via WinRM.

Agentless: No need to install any agent on remote servers.

Core Components of Ansible

1. Ansible Executables

  • /usr/bin/ansible: For ad-hoc commands.
  • /usr/bin/ansible-playbook: For running playbooks.

2. Modules

Modules are reusable scripts (mostly in Python) that perform specific tasks on remote servers. Examples:

  • copy: Copy files.
  • apt: Manage packages on Debian/Ubuntu.
  • yum: Manage packages on Red Hat/CentOS.
  • service: Manage services.

Modules reside on the Control Server but execute on Remote Servers.

3. Plugins

Plugins are Python scripts that extend Ansible’s core functionality and run on the Control Server. Examples include connection plugins, callback plugins, and lookup plugins.

4. Configuration File

  • Default: /etc/ansible/ansible.cfg
  • Manages global settings for Ansible’s behavior.

5. Inventory File (Host File)

Defines the list of remote servers (ARS) to manage. Can be specified as:

  • A simple text file with hostnames/IPs.
  • Inline via command line.
  • Generated dynamically via scripts.

Example:

text[web]
13.127.150.68
3.110.173.45

[db]
1.2.43.5
1.2.43.6
1.2.43.8
1.2.43.9

6. Playbooks

Playbooks are YAML files that define a series of tasks to be executed on remote servers. They use modules to perform actions.

Playbook Structure

  • Play: A mapping of hosts and tasks.
  • Tasks: List of actions, each using a module and parameters.

Example:

text---
- name: Update web servers
  hosts: web
  tasks:
    - name: Install Apache in ubuntu
      ansible.builtin.apt:
        name: "apache2"
        state: latest
    - name: Copy index.html
      ansible.builtin.copy:
        src: index.html
        dest: /var/www/html/index.html
    - name: Starting a Apache Server
      ansible.builtin.service:
        name: "apache2"
        state: started

Writing a Playbook: Step-by-Step

  1. Define the Project: e.g., Set up a web server.
  2. List Steps:
    • Install Apache2.
    • Copy application files.
    • Start Apache2 service.
  3. Choose Modules and Parameters for each step.

Ansible Ad-Hoc Commands

Ad-hoc commands are one-liners used for quick tasks without writing a playbook.

Syntax

textansible <host-pattern> -m <module> -a "<arguments>"

Examples

  • Install Apache2 locally: textansible localhost -m apt -a "name=apache2 state=latest"
  • Stop Apache2 service: textansible localhost -m service -a "name=apache2 state=stopped"
  • Start Apache2 service: textansible localhost -m service -a "name=apache2 state=started"
  • Install Apache2 on multiple servers: textansible all -i 13.127.150.68,3.110.173.45, -m apt -a "name=apache2 state=latest"
  • Start Apache2 on remote servers using SSH key: textansible all -i 13.127.150.68,3.110.173.45, -m service -a "name=apache2 state=started" -u ubuntu -b --key-file=node.pem
  • Run with inventory file: textansible all -i inventory -m apt -a "name=apache2 state=latest"

Additional Ad-Hoc Command Examples

  1. Check disk usage: textansible all -m shell -a "df -h"
  2. Check uptime: textansible all -m command -a "uptime"
  3. Add a user: textansible all -m user -a "name=newuser state=present"
  4. Remove a user: textansible all -m user -a "name=olduser state=absent"
  5. Create a directory: textansible all -m file -a "path=/tmp/testdir state=directory"
  6. Change file permissions: textansible all -m file -a "path=/tmp/testdir mode=0755"
  7. Install multiple packages: textansible all -m apt -a "name=git,curl,wget state=latest"
  8. Reboot servers: textansible all -m reboot
  9. Gather system facts: textansible all -m setup
  10. Ping all servers: textansible all -m ping

Ansible Playbook Execution

Use the ansible-playbook command to run playbooks:

textansible-playbook -i inventory web.yaml -u ubuntu -b --key-file=node.pem
ansible-playbook -i inventory db.yaml -u ubuntu -b --key-file=node.pem
ansible-playbook -i inventory master.yaml -u ubuntu -b --key-file=node.pem

Including and Reusing Tasks

You can include task files within playbooks for modularity:

text- hosts: web
  tasks:
    - debug:
        msg: task1
    - name: Include task list in play
      include: web.yaml
    - name: Include task list in play
      include: db.yaml

Ansible Variables

Variables make playbooks dynamic and reusable.

Types of Variables

  • vars: Defined within the playbook.
  • vars_files: External YAML files containing variables.
  • vars_prompt: Prompt user for input during execution.

Example:

text---
- name: Update web servers
  hosts: web
  vars:
    myname: "Rajeshkumar"
    age: "18"
    packagename: "apache2"
    servicename: "apache2"
  vars_files:
    - "vars.yaml"
  vars_prompt:
    - name: "version"
      prompt: "Which version Do you want to install?"
      private: no
  tasks:
    - name: Install Apache in ubuntu
      ansible.builtin.apt:
        name: "{{ packagename }}"
        state: latest
    - name: Copy index.html
      ansible.builtin.copy:
        src: index.html
        dest: /var/www/html/index.html
    - name: Starting a Apache Server
      ansible.builtin.service:
        name: "{{ servicename }}"
        state: started
    - name: Print variable
      ansible.builtin.debug:
        var: myname
    - name: Print message
      ansible.builtin.debug:
        msg: "My Name is {{ myname }} and My age is {{ age }}"
    - name: Print version
      ansible.builtin.debug:
        var: version
    - name: Register variable
      shell: "find *.txt"
      args:
        chdir: "/root/ansible"
      register: find_output
    - debug:
        var: find_output
    - debug:
        var: find_output.stdout_lines
    - debug:
        var: find_output.stdout_lines[0]

Ansible Roles

Roles are a standardized way to organize playbooks and related files for reuse and sharing.

Role Structure

  • tasks/: Main list of tasks.
  • vars/: Variables used by the role.
  • templates/: Jinja2 templates.
  • handlers/: Handlers for service notifications.
  • files/: Static files to be used.

Example:

text---
- name: Update web servers
  hosts: web
  roles:
    - web

Run with:

textansible-playbook -i inventory site.yaml -u ubuntu -b --key-file=node.pem

Conclusion

Ansible is a powerful tool for automating IT tasks, managing servers, and deploying applications at scale. Its agentless architecture, simple YAML syntax, and vast ecosystem of modules and plugins make it a top choice for DevOps professionals and system administrators. With the foundational knowledge and examples provided above, you can begin automating your infrastructure efficiently and reliably.

Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x