0 / 13 lessons — 0%
Lesson 05 / 13
Variables & facts
Hardcoding "nginx" and "/var/www/html" into every playbook works until you need slightly different values per environment. Variables let one playbook adapt — and they can come from several places, checked in a defined priority order.
| Source | Example |
|---|---|
| Inventory | ansible_user=admin next to a host in inventory.ini |
| group_vars / host_vars files | group_vars/webservers.yml — applies to a whole group |
Playbook vars: | Defined right in the playbook itself |
| Command line | --extra-vars "app_version=1.5" — highest priority, wins ties |
| Facts | Auto-discovered about the host itself — OS, IP, memory, hostname |
- name: Deploy app hosts: webservers vars: app_version: "1.4.0" tasks: - name: Show what Ansible auto-detected about this host debug: msg: "{{ ansible_facts['os_family'] }} on {{ ansible_facts['default_ipv4']['address'] }}" - name: Deploy the pinned version copy: src: "build/app-{{ app_version }}.tar.gz" dest: /opt/app.tar.gz
Facts are gathered automatically at the start of every play (unless you turn it off) — ansible_facts hands you the OS family, IP addresses, total memory, mounted disks, and dozens more details, without you writing any discovery logic yourself.
Try it yourselfRun
ansible webservers -i inventory.ini -m setup against a real host. It dumps every fact Ansible collected — skim it once so you know roughly what's available next time you need one.