The moment of truth has arrived: you are going to use Ansible for the first time against Aurora Store's infrastructure. In this lesson you will create a minimal inventory in aurora-infra/, use the ping module to check that Ansible can reach web1, web2 and db1, and learn how to use the query tools (ansible-inventory, ansible-doc and ansible-config). You will also get to know the most common command-line options and, very importantly, learn how to read Ansible's output: its colors and its states (ok, changed, unreachable, failed). This is a first-contact lesson: the details of inventories, ad hoc commands and modules will come in Module 2.
Contents
- Before you start: checking the lab
- A minimal inventory for Aurora Store
- Your first command:
ansible all -m ansible.builtin.ping - Viewing the inventory with
ansible-inventory - Looking up documentation with
ansible-doc - Viewing the configuration with
ansible-config - Common command-line options
- Reading the output: colors and states
- Saving your work in git
- Before you start: checking the lab
Make sure the machines are running and that SSH access works (you set it up in lesson 1.3):
cd ~/aurora-infra/lab
vagrant status
ssh -i ~/.ssh/aurora_ed25519 [email protected] hostnameIf vagrant status shows all three machines as running and ssh returns web1, you're all set. From now on we will work from the root of the repository:
- A minimal inventory for Aurora Store
Ansible needs to know which machines to work on: that's what the inventory is for. We will create the bare minimum in INI format. Create the file ~/aurora-infra/inventory.ini:
[webservers]
web1 ansible_host=192.168.56.11
web2 ansible_host=192.168.56.12
[dbservers]
db1 ansible_host=192.168.56.21
[all:vars]
ansible_user=vagrant
ansible_ssh_private_key_file=~/.ssh/aurora_ed25519Line-by-line explanation:
[webservers]: opens a group calledwebservers. The following lines are its hosts.web1 ansible_host=192.168.56.11: defines a host with the nameweb1(the one you will use in Ansible) and tells it the actual address to connect to through theansible_hostvariable.[dbservers]anddb1 ...: the same for the database group.[all:vars]: opens a section of variables that apply to theallgroup, that is, to every host:ansible_user=vagrant: remote user to connect as over SSH.ansible_ssh_private_key_file=...: private key to use.
This is just enough to get started. Inventory formats (INI and YAML), nested groups, host ranges and the recommended way to organize variables (
group_vars/host_vars) are covered in the "Inventory Files" and "Inventory Variables" lessons in Module 2.
- Your first command:
ansible all -m ansible.builtin.ping
ansible all -m ansible.builtin.pingRun:
Breaking down the command:
| Part | Meaning |
|---|---|
ansible |
Executable that runs a module against a set of hosts |
all |
Host pattern: which machines it applies to. all = every machine in the inventory |
-i inventory.ini |
Inventory file to use |
-m ansible.builtin.ping |
Module to run, with its fully qualified name (FQCN) |
Important: the
pingmodule is not the networkping(ICMP). It checks the whole chain you saw in the architecture lesson: that Ansible can connect over SSH, authenticate, find Python on the server, copy the module, run it and receive its response. If it responds, the host is ready to be managed.
Expected output:
web1 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": false,
"ping": "pong"
}
db1 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": false,
"ping": "pong"
}
web2 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": false,
"ping": "pong"
}Interpretation:
web1 | SUCCESS: the host name (the one from the inventory, not its IP) and the overall result.SUCCESSappears in green.=> { ... }: the JSON returned by the module, exactly as we described in the architecture lesson."discovered_interpreter_python": "/usr/bin/python3": Ansible has automatically detected which Python interpreter to use on the server."changed": false: the module didn't modify anything (pingnever changes anything)."ping": "pong": the module's response.
Notice also that the order of the hosts may vary between runs (here db1 responded before web2): Ansible works in parallel with several forks and displays each result as soon as it arrives.
Trying it with a group or a host
The host pattern lets you target parts of the inventory:
ansible webservers -i inventory.ini -m ansible.builtin.ping # only web1 and web2
ansible db1 -i inventory.ini -m ansible.builtin.ping # only db1
- Viewing the inventory with
ansible-inventory
ansible-inventoryansible-inventory shows the inventory as Ansible has interpreted it. It doesn't connect to the servers: it only reads files. It's the best way to check that the inventory is correct before using it.
4.1 Tree view: --graph
- Names with
@are groups; the rest are hosts. @ungroupedis an implicit group for hosts that don't belong to any group (it's empty here).
You can add --vars to see the variables too: ansible-inventory -i inventory.ini --graph --vars.
4.2 Full JSON view: --list
{
"_meta": {
"hostvars": {
"db1": {
"ansible_host": "192.168.56.21",
"ansible_ssh_private_key_file": "~/.ssh/aurora_ed25519",
"ansible_user": "vagrant"
},
"web1": {
"ansible_host": "192.168.56.11",
"ansible_ssh_private_key_file": "~/.ssh/aurora_ed25519",
"ansible_user": "vagrant"
},
"web2": {
"ansible_host": "192.168.56.12",
"ansible_ssh_private_key_file": "~/.ssh/aurora_ed25519",
"ansible_user": "vagrant"
}
}
},
"all": {
"children": [
"ungrouped",
"webservers",
"dbservers"
]
},
"dbservers": {
"hosts": [
"db1"
]
},
"webservers": {
"hosts": [
"web1",
"web2"
]
}
}_meta.hostvars: each host's final variables. Notice that the[all:vars]ones have been applied to all three.all.children: the groups hanging offall.- Each group lists its
hosts.
To see a single host: ansible-inventory -i inventory.ini --host web1.
- Looking up documentation with
ansible-doc
ansible-docansible-doc gives you the official documentation without leaving the terminal, and it matches exactly the version you have installed.
5.1 Listing modules: ansible-doc -l
With the full ansible package you will see several thousand modules. To avoid getting lost, filter by collection or by text:
Sample partial output from the first command:
ansible.builtin.add_host Add a host (and alternatively a group) to the ansible-playbook in-memory inventory
ansible.builtin.apt Manages apt-packages
ansible.builtin.apt_key Add or remove an apt key
...
ansible.builtin.ping Try to connect to host, verify a usable python and return `pong' on success
...Each line shows the module's fully qualified name and a short description.
5.2 A module's documentation: ansible-doc ansible.builtin.ping
A pager opens (exit with q) with sections like these (abridged excerpt):
> MODULE ansible.builtin.ping (.../ansible/modules/ping.py)
A trivial test module, this module always returns `pong' on
successful contact. ...
OPTIONS (red indicates it is required):
data Data to return for the `ping' return value.
If this parameter is set to `crash', the module will
cause an exception.
default: pong
type: str
EXAMPLES:
# Test we can logon to 'webservers' and execute python with json lib.
# ansible webservers -m ansible.builtin.ping
...
RETURN VALUES:
- ping Value provided with the `data' parameter.
returned: success
sample: pong
type: strHow to read it:
| Section | What it tells you |
|---|---|
Header (> MODULE ...) |
The module's fully qualified name and a description of what it does |
OPTIONS |
Parameters it accepts, their type, default value and whether they are required (in red) |
EXAMPLES |
Usage examples ready to adapt. Usually the most useful section |
RETURN VALUES |
Fields in the JSON the module returns |
Try the module's data option:
The -a option passes arguments to the module. (Notice that ansible_facts doesn't appear this time: the interpreter had already been detected and Ansible remembers it during the run; depending on the version, you may or may not see it.)
A very handy shortcut is ansible-doc -s ansible.builtin.ping (snippet), which shows a task skeleton with all of its options.
- Viewing the configuration with
ansible-config
ansible-configAnsible has hundreds of configuration settings with default values (number of forks, default inventory, host key checking…). ansible-config lets you look them up.
6.1 Seeing what you've changed: --only-changed
Right now it probably won't show anything (or just a line with CONFIG_FILE() = None): you haven't changed any value yet, so everything is at its default. To see how it works, temporarily change a setting through an environment variable:
DEFAULT_FORKS: the setting's internal name (the forks you saw in the architecture lesson).(env: ANSIBLE_FORKS): where the value comes from; in this case, an environment variable.= 10: the effective value.
This command is your diagnostic tool when Ansible "doesn't behave as you expect": it shows exactly which values differ from the defaults and where they come from.
6.2 Other useful variants
ansible-config dump | less # every setting with its current value
ansible-config list | less # description of each setting
ansible-config view # contents of the ansible.cfg in use (if any)Typing
-i inventory.iniin every command gets repetitive. In the "Configuring Ansible (ansible.cfg)" lesson in Module 2 you will create anansible.cfginaurora-infra/to set the inventory and other project defaults.
- Common command-line options
These options are shared by ansible and, for the most part, by ansible-playbook too:
| Option | Long form | Meaning | Example |
|---|---|---|---|
-i |
--inventory |
Inventory to use | -i inventory.ini |
-m |
--module-name |
Module to run (ansible.builtin.command by default) |
-m ansible.builtin.ping |
-a |
--args |
Module arguments | -a "data=aurora" |
-u |
--user |
Remote user. Careful: if the inventory defines ansible_user, that variable takes precedence over -u |
-u vagrant |
-b |
--become |
Escalate privileges (with sudo by default) |
--become |
-K |
--ask-become-pass |
Prompt for the sudo password |
-b -K |
-l |
--limit |
Limit the run to a subset of the pattern's hosts | --limit web1 |
-v … -vvvv |
--verbose |
More detail in the output (more vs, more detail) |
-vvv |
-o |
--one-line |
Each host's result on a single line | -o |
-f |
--forks |
Number of hosts in parallel | -f 10 |
7.1 --limit
Restricts the pattern to a subset. It's very useful for trying something on a single server before applying it to all of them:
ansible all -i inventory.ini -m ansible.builtin.ping --limit web1
ansible all -i inventory.ini -m ansible.builtin.ping --limit 'web1,db1'7.2 --become
Some operations require administrator privileges. Compare:
- Without
-m, Ansible uses the default module,ansible.builtin.command, which runs the command given in-a. - With
--become, the command runs asrootthroughsudo(thevagrantuser doesn't need a password; on servers where one is required, you would add-K). - Why
CHANGEDifwhoamidoesn't change anything? Remember the architecture lesson:ansible.builtin.commandcan't tell whether a command changed anything, so it always reportschanged. Ad hoc commands and this behavior are covered in "Ad Hoc Commands" (Module 2).
7.3 Verbosity -v to -vvvv
| Level | What it adds |
|---|---|
-v |
More detail on the results |
-vv |
Information about the files and configuration used |
-vvv |
Connection details: SSH commands, temporary directory, module transfer |
-vvvv |
Debugging of the SSH connection itself (includes ssh debug output) |
Try it:
Among other lines, you will see something similar to this (abridged):
<192.168.56.11> ESTABLISH SSH CONNECTION FOR USER: vagrant
<192.168.56.11> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s ... 192.168.56.11 '/bin/sh -c '"'"'( umask 77 && mkdir -p "` echo /home/vagrant/.ansible/tmp `"&& mkdir "` echo /home/vagrant/.ansible/tmp/ansible-tmp-1732615012.43-2741-90812 `" ...'"'"''
<192.168.56.11> PUT /home/student/.ansible/tmp/ansible-local-2741xyz/tmpab12cd TO /home/vagrant/.ansible/tmp/ansible-tmp-1732615012.43-2741-90812/AnsiballZ_ping.py
<192.168.56.11> SSH: EXEC sftp -b - ... '[192.168.56.11]'
<192.168.56.11> SSH: EXEC ssh ... '/bin/sh -c '"'"'/usr/bin/python3 /home/vagrant/.ansible/tmp/ansible-tmp-1732615012.43-2741-90812/AnsiballZ_ping.py && sleep 0'"'"''
<192.168.56.11> SSH: EXEC ssh ... '/bin/sh -c '"'"'rm -f -r /home/vagrant/.ansible/tmp/ansible-tmp-1732615012.43-2741-90812/ > /dev/null 2>&1 && sleep 0'"'"''
web1 | SUCCESS => { ... }These are exactly the steps from the sequence diagram in the previous lesson! Connection with ControlPersist, creation of the temporary directory, copying AnsiballZ_ping.py over sftp, running it with /usr/bin/python3, and the final cleanup. -vvv is your best ally for diagnosing connection problems.
- Reading the output: colors and states
Ansible uses colors so you can assess the result at a glance:
| State | Color | Meaning | Example |
|---|---|---|---|
SUCCESS / ok |
Green | The task ran and changed nothing (the state was already as desired) | ping |
CHANGED / changed |
Yellow | The task ran and modified something on the host | Installing a missing package |
UNREACHABLE! / unreachable |
Red | Could not connect to the host (network, SSH, authentication) | Machine powered off |
FAILED! / failed |
Red | It connected, but the task failed | Command with an error, insufficient permissions |
skipping / skipped |
Cyan | The task was skipped because of a condition (you will see this with playbooks) | — |
Warnings ([WARNING], [DEPRECATION WARNING]) |
Purple/magenta | Warnings that don't stop the run but are worth reviewing | Deprecated options |
The uppercase forms (
SUCCESS,CHANGED) appear inansiblecommands; the lowercase forms (ok,changed) and the finalPLAY RECAPsummary appear when running playbooks (Module 3). The concepts are the same.
8.1 Triggering an UNREACHABLE
Shut down web2 and repeat the ping:
web1 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"},"changed": false,"ping": "pong"}
db1 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"},"changed": false,"ping": "pong"}
web2 | UNREACHABLE!: Failed to connect to the host via ssh: ssh: connect to host 192.168.56.12 port 22: Connection timed out- The
-ooption shows each result on one line, which is convenient when there are many hosts. UNREACHABLE!indicates a connection problem, not a module problem. The message (Connection timed out) points to the cause: the machine isn't responding.- Notice that the
web2failure doesn't preventweb1anddb1from being processed.
Start it again: (cd lab && vagrant up web2).
8.2 Triggering a FAILED
Try listing root's home directory without privileges:
FAILED: Ansible connected and ran the command, but the command exited with an error.rc=2: the command's return code (anything other than 0 = error).- The message explains the cause: insufficient permissions.
With --become it works:
8.3 Telling UNREACHABLE apart from FAILED
flowchart TD
A[Run against a host] --> B{SSH connection<br/>and Python OK?}
B -- No --> U[UNREACHABLE<br/>check network, SSH, user, key]
B -- Yes --> C{Did the module<br/>finish successfully?}
C -- No --> F[FAILED<br/>check arguments, permissions, become]
C -- Yes --> D{Did it modify anything?}
D -- No --> O[OK / SUCCESS]
D -- Yes --> CH[CHANGED]
Knowing which branch you're on tells you where to look for the problem.
- Saving your work in git
Add the inventory to the repository:
cd ~/aurora-infra
git add inventory.ini
git commit -m "Minimal inventory with webservers (web1, web2) and dbservers (db1)"The inventory only contains names, IPs, the user and the path to the key (not the key itself), so it's safe to store. Current layout:
Common Mistakes and Tips
[WARNING]: No inventory was parsed, only implicit localhost is available: you forgot-i inventory.inior you're running it from another directory. Make sure you're in~/aurora-infra.[WARNING]: Could not match supplied host pattern, ignoring: webserver: a typo in the pattern (webserverinstead ofwebservers). Check the names withansible-inventory --graph.UNREACHABLEwithPermission denied (publickey): wrong user or key in the inventory. Try plainsshby hand first, then-vvvv.UNREACHABLEafter recreating a VM with the changed host key warning: delete the old fingerprint withssh-keygen -R 192.168.56.1X(you saw this in lesson 1.3).- Confusing the
pingmodule with the networkping: a host may respond to ICMPpingand fail Ansible's (for example, with no SSH or no Python), and vice versa (if the firewall blocks ICMP). - Getting alarmed by
CHANGEDwithcommand: it's that module's expected behavior, not a real change. - Tip: before running anything against many servers, try it on just one with
--limit.
Exercises
Exercise 1: Selective check
Using the Aurora Store inventory:
pingonly the web servers.pingevery host exceptweb2using--limit.- Display the result on one line per host.
Exercise 2: Investigating with the query tools
- Display the inventory tree including the variables.
- Find out which parameters the
ansible.builtin.aptmodule accepts and locate an example in its documentation that installs a package. (Don't run it: modules are covered in Module 2.) - Run
ansible-config dump --only-changedwith the environment variableANSIBLE_FORKS=20. What does the output tell you?
Exercise 3: Diagnosing states
Predict the state (SUCCESS, CHANGED, FAILED or UNREACHABLE) of each command and check it:
ansible web1 -i inventory.ini -m ansible.builtin.pingansible web1 -i inventory.ini -a "cat /etc/hostname"ansible web1 -i inventory.ini -a "cat /etc/sudoers"ansible web1 -i inventory.ini -m ansible.builtin.ping -u nonexistent_user
Solutions
Exercise 1.
ansible webservers -i inventory.ini -m ansible.builtin.ping
ansible all -i inventory.ini -m ansible.builtin.ping --limit 'all:!web2'
ansible all -i inventory.ini -m ansible.builtin.ping --limit 'all:!web2' -oThe all:!web2 pattern means "everything except web2" (the single quotes stop the shell from interpreting the !). A valid alternative is --limit 'web1,db1'. Patterns are covered in more detail in Module 2.
Exercise 2.
ansible-inventory -i inventory.ini --graph --vars
ansible-doc ansible.builtin.apt # look in EXAMPLES, e.g. "name: foo" with "state: present"
ANSIBLE_FORKS=20 ansible-config dump --only-changedThe last command shows DEFAULT_FORKS(env: ANSIBLE_FORKS) = 20: the number of forks has changed from the default (5) and the source of the change is the environment variable.
Exercise 3.
SUCCESS(green):pingdoesn't change anything.CHANGED(yellow) withrc=0and the outputweb1:commandalways reports changes.FAILED(red) withPermission denied:/etc/sudoerscan only be read byroot; it would work with--become.- The intuitive prediction would be
UNREACHABLE, but the actual result isSUCCESS: the inventory'sansible_user=vagrantvariable takes precedence over the-uoption, so Ansible connects asvagrantanyway. This result surprises many beginners: variable precedence is explained in Module 2 ("Inventory Variables"). If you temporarily removeansible_userfrom the inventory and repeat the command, you will getUNREACHABLEwithPermission denied (publickey), because that user doesn't exist on the server.
Conclusion
You have taken your first hands-on steps with Ansible: you created a minimal inventory.ini in aurora-infra/ with the webservers and dbservers groups, used ansible.builtin.ping to confirm that Aurora Store's three servers are ready to be managed, and learned how to query the inventory (ansible-inventory), the documentation (ansible-doc) and the configuration (ansible-config). You also know how to use the most common options (-i, -m, -a, -u, --become, -v, --limit) and how to interpret the ok, changed, unreachable and failed states. This wraps up Module 1. In Module 2: Ansible Fundamentals you will start with the Inventory Files lesson, where you will turn this minimal inventory into a well-organized one, learn the INI and YAML formats, nested groups and host patterns, and lay the groundwork for managing Aurora Store at any scale.
Ansible Course: From Beginner to Advanced
Module 1: Introduction to Ansible
- What Is Ansible?
- Installing Ansible
- Setting Up the Practice Lab
- Ansible Architecture
- Basic Ansible Commands
Module 2: Ansible Fundamentals
- Inventory Files
- Inventory Variables: group_vars and host_vars
- Configuring Ansible (ansible.cfg)
- Ad Hoc Commands
- Ansible Modules
- Collections and Fully Qualified Names (FQCN)
Module 3: Playbooks
- Introduction to Playbooks
- Essential YAML for Ansible
- Writing Your First Playbook
- Playbook Structure
- Variables and Facts
- Conditionals and Loops
- Registering Results and Debugging Playbooks
Module 4: Roles
- Introduction to Roles
- Creating Roles
- Role Directory Structure
- Using Roles in Playbooks
- Reusing Tasks: include and import
- Role Dependencies and Argument Validation
Module 5: Advanced Playbook Techniques
- Handlers
- Jinja2 Templates
- Filters and Lookups
- Ansible Vault
- Error Handling
- Tags and Selective Execution
- Rolling Deployments and Delegation
- Optimizing Playbooks
Module 6: Ansible Galaxy
- What Is Ansible Galaxy?
- Using Ansible Galaxy
- Managing Dependencies with requirements.yml
- Creating and Sharing Roles
- Creating Your Own Collections
Module 7: Ansible Tower, AWX and Automation Platform
- Introduction to Ansible Tower and AWX
- Installing AWX
- Using AWX: Job Templates and Jobs
- Managing Projects and Inventories
- Credentials, Permissions (RBAC) and Workflows
- Execution Environments and ansible-navigator
Module 8: Ansible for DevOps
- Ansible and Docker
- Ansible and Kubernetes
- CI/CD with Ansible
- Ansible in Cloud Environments
- Ansible and Terraform
Module 9: Ansible Best Practices
- Code Organization
- Security Best Practices
- Performance Tuning
- Code Quality: ansible-lint and yamllint
- Testing Ansible Code with Molecule
Module 10: Advanced Ansible Topics
- Custom Modules
- Dynamic Inventory
- Ansible Plugins
- The Ansible API and ansible-runner
- Event-Driven Ansible
