Master Ansible Playbooks: Core Components, Variables, Loops & Handlers
Ansible playbooks, a powerful configuration management tool, use YAML to define tasks, variables, inventory, conditionals, loops, and handlers; this guide explains core components, syntax, variable scopes, command-line overrides, and provides practical examples for installing services, managing users, and triggering handlers based on changes.
Playbooks Overview
Playbooks are a powerful component of Ansible for configuration management, allowing execution of multiple tasks based on text files and repeatable runs. They use YAML (Yet Another Markup Language), a semi‑structured, declarative language with high readability and easy interaction with scripts.
Core Components
Tasks: task definitions
Variables: variable definitions
ansible_ssh_port: specify SSH port
ansible_ssh_user: specify SSH user
ansible_ssh_pass: SSH login password (plain text)
ansible_sudo_pass: sudo password
Inventory Example
[webserver]
172.16.36.70 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass=zhenping.meInventory Parameters
Common parameters placed after a host in the inventory include template (template file), Handles (handlers), and Roles (role definitions for orchestrating different playbooks).
YAML Syntax
All data structures are indicated by indentation and can be nested. Each line is a key:value pair separated by a colon; multiple pairs on one line use {} and commas. Lists are marked with -. Example:
- hosts: webserver
remote_user: root
tasks:
- name: install nginx
yum: name=nginx state=present
- name: start nginx
service: name=nginx state=started enabled=true
- name: install php-fpm
yum: name=php-fpm state=present
- name: start php-fpm
service: name=php-fpm state=started enabled=true
vars: {}
handlers: []
- hosts: dbserver
remote_user: root
tasks:
- name: install mysql
yum: name=mysql state=presentVariables
Variable names consist of letters, numbers, and underscores and must start with a letter. Types include:
Facts : automatically gathered host attributes, available without explicit declaration.
Custom variables : defined by the user, e.g., via
ansible-playbook test.yml --extra-vars "hosts=www user=zhenping"or through roles.
Host variables : defined after a host entry in the inventory and apply to that host only.
Group variables : defined for a group in the inventory, e.g.:
[webserver]
172.16.36.70
172.16.36.60
[webserver:vars]
var1=value
var2=valuePassing Variables from the Command Line
ansible-playbook script.yml --extra-vars "username=ubunt"
ansible-playbook script.yml -e VARSConditional Tests
Adding a when clause after a task enables conditional execution; the when statement supports Jinja2 syntax. Example (install only on RedHat families):
- hosts: webserver
remote_user: root
tasks:
- name: yum install keepalived
yum: name=keepalived state=present
when: ansible_os_family == "RedHat"
- name: say hello
shell: /bin/echo "hello world"Loops (Iteration)
Use the built‑in item variable with with_items to iterate over a list.
- hosts: webserver
remote_user: root
tasks:
- name: user add
user: name={{ item }} state=present
with_items:
- testuser1
- testuser2
- testuser3
- testuser4Complex items can be dictionaries:
- hosts: webserver
remote_user: root
tasks:
- name: user add
user: name={{ item.name }} state=present group={{ item.groups }}
with_items:
- { name: 'tom2', groups: 'tom' }
- { name: 'tom2', groups: 'tom2' }Handlers (Triggers)
Handlers are tasks that run only when notified by other tasks, typically after a change such as a configuration file update.
- hosts: webserver
remote_user: root
tasks:
- name: yum install nginx
yum: name=nginx state=present
- name: start nginx
service: name=nginx state=started enabled=true
- name: copy configuration file
copy: src=/etc/nginx/nginx.conf dest=/etc/nginx/nginx.conf
notify: restart nginx
handlers:
- name: restart nginx
service: name=nginx state=reloadedSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
