MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Ansible Training Flow

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.

Ansible training flow from ad hoc commands to playbooks and roles across local, remote and inventory groups
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.

StageToolTypical use
Ad hocansibleOne quick task, such as a ping, a package check or a restart
Playbookansible-playbookAn ordered set of tasks you can repeat, stored in YAML
Roleansible-playbook + ansible-galaxyA 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

ErrorLikely causeFix
UNREACHABLE! ... Permission denied (publickey)Wrong SSH user or keySet ansible_user, use --private-key, or run ssh-copy-id first
Missing sudo passwordbecome needs a passwordAdd -K (--ask-become-pass) or configure sudo rules
Could not match supplied host patternGroup or host name not in the inventoryCheck the names with ansible-inventory --graph
provided hosts list is emptyNo -i was given and no default inventory existsPass -i or set inventory in ansible.cfg
the role 'nginx' was not foundRole is not in roles_pathPut the role under ./roles or set roles_path
Python interpreter errorsPython is missing on the managed hostInstall Python 3 or set ansible_python_interpreter

Best practices while following the flow

  • Use fully qualified module names such as ansible.builtin.package so it is always clear which module runs.
  • Prefer modules over command/shell so that tasks stay idempotent.
  • Run --check --diff before applying changes to shared or production hosts.
  • Keep secrets out of plain-text group_vars. Encrypt them with ansible-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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
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.

Related Posts

How Ansible Automates Cisco IOS and IOS XE Network Devices

Introduction Managing multiple Cisco routers and switches manually can become time-consuming as a network grows. Network engineers regularly configure interfaces, check device status, update settings, and troubleshoot…

Read More

Configuration Management in DevOps: Concepts, Tooling, and a Practical Workflow

This guide explains how configuration management works in modern DevOps teams, compares common tools, and shows a practical Ansible example. It also preserves the original SlideShare reference from the legacy post.

Read More

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…

Read More

Ansible Labs & Assignment & Excercise

Ansible Adhoc Commands Lab & Excercise โ€“ Part 1 Ansible Windows Adhoc Commands Lab & Excercise โ€“ Part 2 Ansible Inventory Lab & Excercise โ€“ Part 3…

Read More

Interview Questions & Answers for Ansible

Ansible Describe each of the following components in Ansible, including the relationship between them: Task Module Play Playbook Role How Ansible is different from other Automation tools?…

Read More

Configure Ansible for Deployment of Datadog Agent in Multiple Linux Servers

Step 1 – Install Ansible tool in your workstation Step 2 – Write a Ansible playbook Step 3 – Create a Ansible inventory file consist of Multiple…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x