Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours scrolling social media and waste money on things we forget, but won’t spend 30 minutes a day earning certifications that can change our lives.
Master in DevOps, SRE, DevSecOps & MLOps by DevOpsSchool!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

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

Here is a comprehensive, professional-quality Ansible tutorial based on your notes, structured as a long-form guide. Every topic, term, and example is included, with deep explanations and practical demonstrations.



1. What is Ansible?

Ansible is an open-source configuration management, application deployment, and server orchestration tool created by Red Hat. It enables IT professionals and developers to automate the management of servers and software, ensuring consistent and repeatable outcomes.

Key Points:

  • Configuration Management Tool: Automates the setup, maintenance, and configuration of servers.
  • Server Management Tool: Efficiently manages large groups of servers from a single control point.
  • Written in Python: Ansible is built using Python, making it cross-platform and highly extensible.

Product Releases:

  • Ansible (CLI): Free command-line tool for automation.
  • Ansible Tower: Paid UI-based solution for enterprise teams (now called Red Hat Ansible Automation Platform).
  • AWX: Free, open-source UI for Ansible (community-supported version of Tower).

2. Why Do We Need Ansible?

Common Use Cases:

  • IT Teams: Deploy and configure system software, antivirus, company policies, etc.
  • Developers: Automate the deployment of application code and related services.
  • Any Resource Management: If you need to change files, directories, users, packages, or services across many servers, Ansible is ideal.

Benefits of Using Ansible:

  • Cost Savings: Apply changes to hundreds or thousands of servers at once, reducing manual effort.
  • Time Savings: Execute bulk operations quickly and repeatably.
  • Improved Quality: Achieve consistent, predictable changes on every server.

Typical Server Management Tasks:

  • Managing files and directories
  • Installing or removing packages (apt, yum)
  • Controlling services (start, stop, restart)
  • Executing shell or command tasks
  • Managing users and groups

3. Alternatives to Ansible

Other popular configuration management tools include:

ToolLanguageAgent/AgentlessNotable Use
ChefRubyAgent-basedCode-driven config mgmt.
PuppetRubyAgent-basedInfrastructure as code
CFEngineCAgent-basedLightweight, scalable
SaltStackPythonBothFast remote execution

Ansible’s main advantage: Agentless operation—no special software required on managed hosts.


4. How Does Ansible Work? (Architecture Overview)

Key Terminologies:

  • ACS: Ansible Control Server (the machine from which you run Ansible).
  • ARS: Ansible Remote Server (the target machine(s) being managed).

Architecture Flow:

Human (You)
   |
   V
Ansible Control Server (ACS)
   |
   V
Ansible Remote Server(s) (ARS)

Requirements:

ComponentACS (Control)ARS (Remote)
OSLinux 64-bitLinux/Windows/others
PythonYesYes (Linux), .NET/PS (Windows)
AnsibleYesNo
AgentNo (agentless)No (agentless)
CommunicationN/ASSH (Linux), WinRM (Windows)

Agentless: No Ansible agent is installed on remote servers; communication is via SSH (Linux/Unix) or WinRM (Windows).


5. Core Components of Ansible

5.1. Executables

Main CLI tools found in /usr/bin/:

  • ansible: Runs single tasks (ad-hoc).
  • ansible-playbook: Runs playbooks (multiple tasks).
  • ansible-galaxy: Manages Ansible roles and collections.

5.2. Modules

A module is a reusable, standalone script (written in Python) that performs a specific task. They reside on the ACS and run remotely on ARS.

Examples:

  • copy (copies files)
  • apt, yum (manage packages)
  • service (manage services)
  • user (manage users)
  • See full list here

5.3. Plugins

A plugin is a piece of code that adds extra functionality to Ansible itself (runs on ACS). Types include connection plugins, callback plugins, lookup plugins, etc.

See all plugins here

5.4. Configuration File

The main config file is:

  • /etc/ansible/ansible.cfg

Ansible config example and details

5.5. Inventory (Host File)

The inventory is a file or script that lists the IPs/hostnames of the ARS to be managed.

Inventory Example:

[web]
13.127.150.68
3.110.173.45Code language: CSS (css)

[db]

1.2.43.5 1.2.43.6

You can provide the inventory as a file, inline on the command line, or generate it dynamically.

5.6. Playbook

A playbook is a YAML file that defines a set of tasks to execute on remote hosts using Ansible modules.

Sample Playbook:

---
- 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 Apache Server
      ansible.builtin.service:
        name: "apache2"
        state: started
Code language: JavaScript (javascript)

More playbook examples


6. How to Write a Playbook

Step-by-Step:

  1. Define the Project: e.g., “Set up a web server”.
  2. List Steps: What should happen? (install apache2, copy files, start service).
  3. For Each Step: Find the relevant module and parameters.

Example Playbook for Webserver:

---
- name: Setup Webserver
  hosts: web
  tasks:
    - name: Install Apache2
      ansible.builtin.apt:
        name: apache2
        state: latest
    - name: Copy app file
      ansible.builtin.copy:
        src: app.html
        dest: /var/www/html/app.html
    - name: Start apache2
      ansible.builtin.service:
        name: apache2
        state: started
Code language: JavaScript (javascript)

7. Ansible Ad-Hoc Commands

Ad-hoc commands let you run one-off tasks without writing a playbook.

General Syntax:

ansible <target> -m <module> -a "<module options>"
Code language: HTML, XML (xml)

Examples (local):

# Install Apache2 package
ansible localhost -m apt -a "name=apache2 state=latest"

# Stop Apache2 service
ansible localhost -m service -a "name=apache2 state=stopped"

# Start Apache2 service
ansible localhost -m service -a "name=apache2 state=started"
Code language: PHP (php)

10 More Local Ad-Hoc Command Examples:

# 1. Create a user
ansible localhost -m user -a "name=raj password=abc123"

# 2. Add group
ansible localhost -m group -a "name=developers"

# 3. Copy a file
ansible localhost -m copy -a "src=/tmp/a.txt dest=/tmp/b.txt"

# 4. Fetch a file
ansible localhost -m fetch -a "src=/tmp/b.txt dest=/tmp/"

# 5. Run a shell command
ansible localhost -m shell -a "uptime"

# 6. Change file permissions
ansible localhost -m file -a "path=/tmp/b.txt mode=0644"

# 7. Install multiple packages
ansible localhost -m apt -a "name=git,curl state=present"

# 8. Reboot the system
ansible localhost -m reboot

# 9. Get disk space info
ansible localhost -m command -a "df -h"

# 10. List all users
ansible localhost -m shell -a "cat /etc/passwd"
Code language: PHP (php)

Running Ad-Hoc Commands on Multiple Servers

Using Inline Inventory:

ansible all -i 13.127.150.68,3.110.173.45, -m apt -a "name=apache2 state=latest"
ansible all -i 13.127.150.68,3.110.173.45, -m service -a "name=apache2 state=started" -u ubuntu -b --key-file=node.pem
Code language: JavaScript (javascript)

Using Inventory File:

ansible all -i inventory -m apt -a "name=apache2 state=latest" -u ubuntu -b --key-file=node.pem
ansible all -i inventory -m service -a "name=apache2 state=started" -u ubuntu -b --key-file=node.pem
Code language: JavaScript (javascript)

8. Running Ansible Playbooks

Syntax:

ansible-playbook -i <inventory> <playbook.yaml> -u <user> -b --key-file=<private-key>
Code language: HTML, XML (xml)

Examples:

ansible-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

Inventory file example:

[web]
13.127.150.68
3.110.173.45Code language: CSS (css)

[db]

1.2.43.5 1.2.43.6 1.2.43.8 1.2.43.9


9. Playbook Task Inclusion

You can include other playbooks or tasks within your main playbook:

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

- hosts: db
  tasks:
    - debug: msg="task1"
    - name: Include task list in play
      include: web.yaml
    - name: Include task list in play
      include: db.yaml
Code language: PHP (php)

10. Ansible Variables

Variables allow you to parametrize your playbooks for flexibility and reuse.

Variable Sources:

  • Inline: Defined directly in playbook under vars:
  • Files: Separate YAML files loaded with vars_files:
  • Prompt: Ask user input with vars_prompt:

Example:

---
- 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 name and age
      ansible.builtin.debug:
        msg: "My Name is {{ myname }} and My age is {{ age }}"
    - name: Print version from prompt
      ansible.builtin.debug:
        var: version
    - name: Register and print file list
      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]
Code language: PHP (php)

Running Playbook:

ansible-playbook -i inventory vars.yaml -u ubuntu -b --key-file=node.pem

More variable examples


11. Ansible Roles

Roles provide a standard way to organize playbooks and make code reusable and shareable.

Role Directory Structure:

roles/
  web/
    tasks/
      main.yaml
    handlers/
      main.yaml
    files/
    templates/
    vars/
      main.yaml
    defaults/
      main.yaml

Using a Role in a Playbook:

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

Run:

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

Key Concepts:

  • Tasks: Steps to be executed.
  • Vars: Variables specific to the role.
  • Templates: Jinja2 templates to render config files dynamically.
  • Handlers: Special tasks triggered by “notify” for things like restarts.
  • Files: Static files to be copied to the remote host.

Benefits:

  • Standardization
  • Shareability (e.g., via Ansible Galaxy)
  • Cleaner code organization

12. Summary: Why Ansible is Essential

  • Agentless: No extra software on managed hosts
  • Idempotent: Safe to run multiple times (won’t break things)
  • Readable: Human-friendly YAML syntax
  • Extensible: Easily integrated with cloud, containers, CI/CD, etc.
  • Community Powered: Thousands of modules and roles available

Quick Reference Table

TermMeaning
ACSAnsible Control Server (where you run Ansible)
ARSAnsible Remote Server (where tasks are applied)
ModuleSmall, reusable unit of work (e.g., apt, copy, service)
PluginExtends Ansible (connection, lookup, callback, etc.)
InventoryList of managed hosts
PlaybookOrdered set of tasks in YAML
VariableParameter for use in playbooks/tasks
RoleDirectory structure for reusability

Further Resources


If you need more detailed sections, live scenarios, or want to expand on topics like dynamic inventories, Ansible Galaxy, or advanced Jinja2 templating, just let me know!

Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

Certification Courses

DevOpsSchool has introduced a series of professional certification courses designed to enhance your skills and expertise in cutting-edge technologies and methodologies. Whether you are aiming to excel in development, security, or operations, these certifications provide a comprehensive learning experience. Explore the following programs:

DevOps Certification, SRE Certification, and DevSecOps Certification by DevOpsSchool

Explore our DevOps Certification, SRE Certification, and DevSecOps Certification programs at DevOpsSchool. Gain the expertise needed to excel in your career with hands-on training and globally recognized certifications.

0
Would love your thoughts, please comment.x
()
x