Ansible Playbooks: Automating Servers Without Agents

Ansible Playbooks

Ansible configures machines over SSH without installing an agent on each host. You describe the desired state in YAML, and Ansible connects, checks the current state, and changes only what differs.

Three files make up most projects: an inventory that lists hosts, a playbook that lists plays and tasks, and optional roles that package reusable tasks.

bash ansible all -i inventory.ini -m ping ansible-playbook -i inventory.ini site.yml --check --diff ansible-playbook -i inventory.ini site.yml

The --check flag runs in dry mode and --diff shows the file changes it would make. Always run both before touching production.

Key habits that keep playbooks safe:

- Use modules such as apt, template, and service instead of raw shell, because modules are idempotent. - Store secrets with ansible-vault encrypt vars/secrets.yml. - Tag tasks with tags: so you can run a subset with --tags nginx. - Keep variables in groupvars/ and hostvars/ rather than hard-coding them.

A handler runs only when a notified task reports a change, which is useful for restarting a service after a config update. Ansible reports changed for a task that modified something and ok for one that was already correct, so a second run of a well-written playbook should show almost no changes.