Now that you’ve successfully created and run your first Ansible playbook, it’s time to expand your skills. In this post, we’ll explore how to structure more powerful and reusable playbooks using:
- Multiple tasks
- Variables
- Handlers
- Tags
These concepts will help you build automation that is cleaner, modular, and more efficient.
Multiple Tasks in a Playbook
Playbooks often contain more than one task. Here’s how you can install multiple packages in sequence:
---
- name: Install useful tools
hosts: home_servers
become: true
tasks:
- name: Install htop
apt:
name: htop
state: present
- name: Install curl
apt:
name: curl
state: present
- name: Install git
apt:
name: git
state: present
Using Variables
Variables make your playbooks flexible and reusable.
---
- name: Install tools using variables
hosts: home_servers
become: true
vars:
tools:
- htop
- curl
- git
tasks:
- name: Install each tool
apt:
name: "{{ item }}"
state: present
loop: "{{ tools }}"
This way, you can manage your tool list in one place.
Introducing Handlers
Handlers are tasks that only run when notified by another task. A common use case is restarting a service only when its config file changes.
---
- name: Update SSH config and restart if needed
hosts: home_servers
become: true
tasks:
- name: Update sshd_config
copy:
src: sshd_config
dest: /etc/ssh/sshd_config
notify: Restart SSH
handlers:
- name: Restart SSH
service:
name: ssh
state: restarted
Using Tags to Control Task Execution
Tags allow you to run only specific parts of your playbook:
tasks:
- name: Install UFW
apt:
name: ufw
state: present
tags:
- firewall
Run the playbook with only firewall tasks:
ansible-playbook tools.yml --tags firewall
Tips for Reusability
- Avoid hardcoding values — use variables instead
- Use handlers for conditional actions
- Group related tasks with tags
- Begin thinking about using
roles(we’ll cover these in Part 4!)
Coming Up Next
In Part 3, we’ll build on this foundation by exploring real-world use cases: creating users, managing services, setting up scheduled jobs, and more using core Ansible modules.
You’re one step closer to becoming an automation pro. Keep going!