Understanding Variables
Variables make playbooks reusable across environments. They can be defined in playbooks, inventories, command-line arguments, and roles
Variable Example
---
- hosts: webservers
vars:
web_package: nginx
tasks:
- name: Install package
apt:
name: "{{ web_package }}"
state: present
Handlers
Handlers run only when notified by a changed task.
Example:
tasks:
- name: Update nginx config
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify:
- Restart Nginx
handlers:
- name: Restart Nginx
service:
name: nginx
state: restarted
Jinja2 Templates
Template file:
server {
listen {{ nginx_port }};
}
Playbook:
vars:
nginx_port: 8080
Variable Files
vars_files:
- vars/common.yml
Example:
nginx_port: 8080
environment: production
Best Practices
- Use variables instead of hardcoded values.
- Keep secrets outside playbooks.
- Use templates for configuration files.
- Use handlers for service restarts






