Move from one-off commands to a playbook — a YAML file describing the desired state of a machine — then run it and watch Ansible report what changed.
Why: a playbook is a repeatable, version-controlled description of how a machine should be set up. It is a YAML list of plays; each play targets a group of hosts and runs an ordered list of tasks. Each task calls one module with arguments and gets a readable name. Indentation matters in YAML — two spaces, never tabs.
# site.yml
- name: Configure my machine
hosts: local
tasks:
- name: Create a working directory
ansible.builtin.file:
path: /tmp/ansible-demo
state: directory
- name: Write a file
ansible.builtin.copy:
dest: /tmp/ansible-demo/hello.txt
content: "Managed by Ansible\n"ansible-playbook runs the file against the hosts in your inventory. The output shows each task and a colour-coded result per host: ok (already correct), changed (Ansible made a change), or failed. The PLAY RECAP at the end summarizes the counts.
Run it
ansible-playbook site.yml -i inventory.iniConfirm the file is really there
cat /tmp/ansible-demo/hello.txtWhy: this is the heart of Ansible. Run the same playbook a second time and every task reports "ok" with changed=0 — because the desired state already matches reality, so Ansible does nothing. This is idempotency: describe the end state, and running repeatedly is always safe. It is what separates Ansible from a shell script that blindly re-runs commands.
first run: changed=2 (created the dir and the file)
second run: changed=0 (already in the desired state — no-op)
third run: changed=0 (idempotent: safe to run any number of times)Why: before changing a real machine, you want a dry run. --check runs the playbook without making changes and reports what WOULD change; --diff additionally shows the line-by-line differences for files. Together they are your "plan" step — run them before applying to anything you care about.
Dry run: report what would change, change nothing
ansible-playbook site.yml -i inventory.ini --checkAlso show file content differences
ansible-playbook site.yml -i inventory.ini --check --diff