Section 1: Getting started with Ansible
Inventory and ad hoc commands
The inventory tells Ansible which machines exist and how to group them. Start with a simple YAML inventory for our lab:
# inventory/lab.yml
all:
children:
web:
hosts:
web1:
ansible_host: 192.168.64.11
web2:
ansible_host: 192.168.64.12
db:
hosts:
db1:
ansible_host: 192.168.64.21
vars:
ansible_user: admin
ansible_ssh_private_key_file: ~/.ssh/lab_ed25519
Groups (web, db) let you target sets of servers. Host names like web1 are aliases; ansible_host holds the real address.
A project configuration file
Create ansible.cfg in your project so you do not repeat options:
[defaults]
inventory = inventory/lab.yml
stdout_callback = yaml
Ansible reads ansible.cfg from the current directory, which keeps settings with the project.
Check connectivity
ansible all -m ansible.builtin.ping
This is not ICMP ping. It connects over SSH, runs a tiny module with Python and returns pong. If it fails, fix SSH first: user, key, host key verification and firewall.
Ad hoc commands
For quick one off tasks, run a module directly:
ansible web -m ansible.builtin.command -a "uptime"
ansible all -m ansible.builtin.setup -a "filter=ansible_distribution*"
ansible db -b -m ansible.builtin.apt -a "name=htop state=present update_cache=true"
-mchooses the module,-apasses arguments.-bmeans become, running with privilege escalation (sudo by default).- The
setupmodule gathers facts: OS, IP addresses, memory and much more, available later as variables.
Patterns
Target hosts flexibly: web:db for both groups, all:!db for everything except the database, web1 for one host. Use --limit with playbooks to narrow a run, which is invaluable when testing changes on one server first.
When to use ad hoc commands
Ad hoc commands are great for investigation, such as checking disk space on all servers, and for emergencies. Anything you would do twice belongs in a playbook, where it is reviewed, versioned and repeatable.