This page walks through the Ansible training flow step by step. It starts with ad hoc commands, moves on to playbooks and finishes with roles. At each stage the target grows from localhost to a single remote host, then to inventory groups, groups of groups and per-environment inventory directories, with a working example for every step.

using ADHOC command
Do one task in ONE MACHINE(localhost)
Do one task in ONE REMOTE MACHINE
Do one task in MULTIPLE REMOTE MACHINES using Inventory
Do one task in MULTIPLE REMOTE MACHINES using group in Inventory
using Playbook(Program)
Do Multiple tasks(Playbook) in ONE MACHINE(localhost)
Do Multiple tasks(Playbook) in ONE REMOTE MACHINE
Do Multiple tasks(Playbook) in MULTIPLE REMOTE MACHINE using Inventory
Do Multiple tasks(Playbook) in MULTIPLE REMOTE MACHINE using group in Inventory
Do Multiple tasks(Playbook) in MULTIPLE REMOTE MACHINE using group of group in Inventory
Do Multiple tasks(Playbook) in MULTIPLE REMOTE MACHINE using environment directory Inventory
using Role(Program)
Do One Role in in ONE MACHINE(localhost)
Do Multiple Roles in ONE REMOTE MACHINE
Do Multiple Roles in MULTIPLE REMOTE MACHINE using Inventory
Do Multiple Roles in MULTIPLE REMOTE MACHINE using group in Inventory
Do Multiple Roles in MULTIPLE REMOTE MACHINE using group of group in Inventory
Do Multiple Roles in MULTIPLE REMOTE MACHINE using environment directory InventoryCode language: PHP (php)
How the training flow is structured
The outline above changes two things at a time: what you run (one ad hoc task, a playbook with several tasks, or reusable roles) and where you run it (localhost, one remote host, an inventory, inventory groups, groups of groups, and separate environment inventories). Learning in this order means each new idea builds on one you have already tested.
| Stage | Tool | Typical use |
|---|---|---|
| Ad hoc | ansible | One quick task, such as a ping, a package check or a restart |
| Playbook | ansible-playbook | An ordered set of tasks you can repeat, stored in YAML |
| Role | ansible-playbook + ansible-galaxy | A packaged, reusable unit of tasks, handlers, templates and variables |
Prerequisites: Ansible installed on a Linux or macOS control node (pip install ansible or your distribution's package), SSH key access to the managed Linux hosts, Python on those hosts, and a user who can run sudo there.
Stage 1: ad hoc commands
Ad hoc commands run a single module against a host pattern. Start on localhost, which Ansible always knows about even without an inventory.
# One task on ONE MACHINE (localhost)
ansible localhost -m ansible.builtin.ping
ansible localhost -m ansible.builtin.command -a "uptime"
# One task on ONE REMOTE MACHINE (the trailing comma makes it an inline host list)
ansible all -i 192.168.1.10, -u ubuntu -m ansible.builtin.pingCode language: CSS (css)
Next, create an inventory file so you can target many hosts by name or by group. The [prod:children] section is a group of groups, which the playbook stage uses later.
# inventory.ini
[web]
web1 ansible_host=192.168.1.11
web2 ansible_host=192.168.1.12
[db]
db1 ansible_host=192.168.1.21
[prod:children]
web
db
[all:vars]
ansible_user=ubuntuCode language: PHP (php)
# One task on MULTIPLE REMOTE MACHINES using the inventory
ansible all -i inventory.ini -m ansible.builtin.ping
# One task on a GROUP in the inventory (-b = become/sudo)
ansible web -i inventory.ini -b -m ansible.builtin.package -a "name=nginx state=present"Code language: PHP (php)
A successful ping prints something similar to web1 | SUCCESS => { "changed": false, "ping": "pong" } for each host. Ansible's ping module is not ICMP. It checks that Ansible can log in over SSH and run Python on the host.
Stage 2: playbooks
A playbook holds several tasks in order. The hosts: line decides where they run. Begin with localhost, where connection: local skips SSH entirely.
# local.yml - multiple tasks on ONE MACHINE (localhost)
- name: Local practice playbook
hosts: localhost
connection: local
gather_facts: false
tasks:
- name: Create a working directory
ansible.builtin.file:
path: /tmp/ansible-demo
state: directory
mode: "0755"
- name: Write a file
ansible.builtin.copy:
dest: /tmp/ansible-demo/hello.txt
content: "Hello from Ansible\n"Code language: PHP (php)
# web.yml - multiple tasks on remote machines
- name: Configure web servers
hosts: web
become: true
tasks:
- name: Install nginx
ansible.builtin.package:
name: nginx
state: present
- name: Ensure nginx is running and enabled
ansible.builtin.service:
name: nginx
state: started
enabled: trueCode language: CSS (css)
ansible-playbook local.yml
# ONE REMOTE MACHINE: limit the run to a single host
ansible-playbook -i inventory.ini web.yml --limit web1
# MULTIPLE REMOTE MACHINES using a group (hosts: web)
ansible-playbook -i inventory.ini web.yml
# Group of groups: set hosts: prod in the play, or narrow the run with --limit
ansible-playbook -i inventory.ini web.yml --limit prod
# Preview the changes without applying them
ansible-playbook -i inventory.ini web.yml --check --diffCode language: PHP (php)
Run each playbook twice. On the second run, every task should report ok rather than changed. That is idempotence, the main reason to use modules instead of raw shell commands.
Environment directory inventory
Real projects keep a separate inventory for each environment, with variables stored next to it. When -i points to a directory, Ansible reads every inventory file in it and loads the group_vars and host_vars folders inside it.
inventories/
dev/
hosts.ini
group_vars/
all.yml # e.g. app_env: dev
web.yml
prod/
hosts.ini
group_vars/
all.yml # e.g. app_env: prod
web.ymlCode language: PHP (php)
# Check what Ansible sees before running anything
ansible-inventory -i inventories/dev --graph
ansible-inventory -i inventories/dev --host web1
# Same playbook, different environment
ansible-playbook -i inventories/dev web.yml
ansible-playbook -i inventories/prod web.ymlCode language: PHP (php)
Note: The playbook stays the same in every environment. Only the inventory and its variables change. Do not hard-code environment-specific values inside tasks.
Stage 3: roles
Roles package tasks, handlers, templates, files and default variables in a standard directory layout, so the same logic can be reused in many playbooks.
ansible-galaxy role init roles/common
ansible-galaxy role init roles/nginx
# Resulting layout (per role)
# roles/nginx/tasks/main.yml <- tasks
# roles/nginx/handlers/main.yml <- handlers (e.g. restart nginx)
# roles/nginx/defaults/main.yml <- lowest-priority variables
# roles/nginx/vars/main.yml <- higher-priority variables
# roles/nginx/templates/ <- Jinja2 templates
# roles/nginx/files/ <- static files
# roles/nginx/meta/main.yml <- metadata and role dependenciesCode language: PHP (php)
Move the nginx tasks from web.yml into roles/nginx/tasks/main.yml (just the task list, with no hosts: or tasks: keys). Then call the roles from a short playbook:
# site.yml
- name: Apply one role on localhost
hosts: localhost
connection: local
become: true
roles:
- common
- name: Apply multiple roles on web servers
hosts: web # or a group of groups such as prod
become: true
roles:
- common
- nginxCode language: PHP (php)
ansible-playbook -i inventories/dev site.yml
ansible-playbook -i inventories/prod site.yml --limit web1
An ansible.cfg in the project root saves you from typing the same options on every run:
[defaults]
inventory = inventories/dev
roles_path = ./roles
Common errors and fixes
| Error | Likely cause | Fix |
|---|---|---|
UNREACHABLE! ... Permission denied (publickey) | Wrong SSH user or key | Set ansible_user, use --private-key, or run ssh-copy-id first |
Missing sudo password | become needs a password | Add -K (--ask-become-pass) or configure sudo rules |
Could not match supplied host pattern | Group or host name not in the inventory | Check the names with ansible-inventory --graph |
provided hosts list is empty | No -i was given and no default inventory exists | Pass -i or set inventory in ansible.cfg |
the role 'nginx' was not found | Role is not in roles_path | Put the role under ./roles or set roles_path |
| Python interpreter errors | Python is missing on the managed host | Install Python 3 or set ansible_python_interpreter |
Best practices while following the flow
- Use fully qualified module names such as
ansible.builtin.packageso it is always clear which module runs. - Prefer modules over
command/shellso that tasks stay idempotent. - Run
--check --diffbefore applying changes to shared or production hosts. - Keep secrets out of plain-text
group_vars. Encrypt them withansible-vault. - Leave SSH host key checking enabled outside throwaway labs.
- Keep inventories, playbooks and roles in Git so every change can be reviewed.
Frequently asked questions
What is the difference between an Ansible ad hoc command and a playbook?
An ad hoc command runs one module once from the command line, which suits quick checks and one-off fixes. A playbook is a YAML file with ordered tasks that you can rerun, review and keep in version control.
When should I convert a playbook into roles?
Convert it when the same tasks are needed in more than one playbook or project, or when one playbook grows too long to read easily. Roles give tasks, handlers, templates and variables a standard place to live.
How do I create a group of groups in an Ansible inventory?
In INI format, add a section such as [prod:children] and list existing group names under it. In YAML inventories, list the groups under a children: key.
How do I run a playbook on only one host from my inventory?
Use --limit hostname, for example ansible-playbook -i inventory.ini web.yml --limit web1. The play's hosts: pattern still applies, and --limit narrows it further.
How do I manage dev and prod with the same playbook?
Create one inventory directory per environment, each with its own hosts file and group_vars. Select the environment at run time with -i inventories/dev or -i inventories/prod.
Related tutorials
- The Complete Ansible Tutorial: Concepts, Architecture, Playbooks, and Real-World Examples
- Ansible: Command line tools with example in Ansible
- System administrator Tasks in OS & Servers using ansible
- TOP 65+ INTERVIEW QUESTIONS FOR ANSIBLE
- More Ansible tutorials
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals