You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Variables and facts make your Ansible automation dynamic and reusable. Variables let you parameterise playbooks, while facts provide real-time information about your managed nodes.
---
- name: Deploy application
hosts: webservers
vars:
app_name: myapp
app_port: 8080
app_env: production
tasks:
- name: Print app info
debug:
msg: "Deploying {{ app_name }} on port {{ app_port }} ({{ app_env }})"
---
- name: Deploy application
hosts: webservers
vars_files:
- vars/common.yml
- vars/{{ env }}.yml
# Single variable
ansible-playbook site.yml -e "app_env=staging"
# Multiple variables
ansible-playbook site.yml -e "app_env=staging app_port=9090"
# Variables from a file
ansible-playbook site.yml -e "@vars/overrides.yml"
Ansible has a well-defined hierarchy for variable precedence. When the same variable is defined in multiple places, the highest precedence wins:
| Priority | Source | Notes |
|---|---|---|
| 1 (lowest) | Role defaults (defaults/main.yml) | Easily overridden |
| 2 | Inventory file or script group vars | |
| 3 | group_vars/all | |
| 4 | group_vars/<group> | |
| 5 | Inventory file or script host vars | |
| 6 | host_vars/<host> | |
| 7 | Play vars | |
| 8 | Play vars_files | |
| 9 | Play vars_prompt | |
| 10 | Task vars (in a task block) | |
| 11 | include_vars | |
| 12 | set_fact / register | |
| 13 | Role params | |
| 14 (highest) | Extra vars (-e) | Always wins |
Tip: Extra vars (
-e) from the command line always take the highest precedence --- use them for overriding values at runtime.
Facts are system properties automatically gathered from managed nodes at the beginning of each play (unless gather_facts: false is set).
ansible webservers -m setup
| Fact | Example Value | Description |
|---|---|---|
ansible_hostname | web1 | Short hostname |
ansible_fqdn | web1.example.com | Fully qualified domain name |
ansible_os_family | Debian | OS family (Debian, RedHat, etc.) |
ansible_distribution | Ubuntu | Distribution name |
ansible_distribution_version | 22.04 | Distribution version |
ansible_default_ipv4.address | 192.168.1.10 | Default IPv4 address |
ansible_memtotal_mb | 8192 | Total memory in MB |
ansible_processor_vcpus | 4 | Number of vCPUs |
ansible_architecture | x86_64 | CPU architecture |
tasks:
- name: Show OS information
debug:
msg: "{{ ansible_distribution }} {{ ansible_distribution_version }} ({{ ansible_os_family }})"
- name: Set worker processes based on CPU count
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
vars:
worker_processes: "{{ ansible_processor_vcpus }}"
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.