Chapter #20: How to Create Ansible Plays and Playbooks
In this chapter, we explore how to install packages, manage services, copy files, and automate system configuration using Ansible modules

In this chapter, we will explain how to create Ansible Plays and Playbooks using Ansible modules.
Ansible ships with standalone scripts called modules that are used in playbooks for the execution of specialized tasks on remote nodes.
Modules come in handy for automating tasks such as package management, archiving, and copying files, to mention just a few. They allow you to make tweaks on configuration files and manage devices such as routers, switches, load balancers, firewalls, and a host of other devices.
The objective of this subtopic is to give you an overview of various tasks that can be accomplished by Ansible modules:
Package Management in Linux
Package management is one of the most essential and frequent tasks carried out by systems administrators. Ansible ships with modules that help you execute package management tasks both in RedHat and Debian-based systems.
They are relatively easy to guess. There is the apt module for APT package management for Debian-based systems, the old yum module for YUM package management, and the dnf module associated with newer RHEL distributions.
Below are a few examples of how the modules can be used in a playbook:
Example 1: Installing the Apache Web Server on RHEL
This playbook installs the Apache web server (httpd
) on RHEL-based systems using the dnf
module. It targets all hosts in the webservers
group and ensures that the latest version of Apache is installed.
If the package is missing, it will be installed; if it's outdated, it will be upgraded; otherwise, no changes will be made.
---
- name: install Apache webserver
hosts: webservers
tasks:
- name: install httpd
dnf:
name: httpd
State: latest
Example 2: Installing the Apache Web Server on Debian
This playbook installs the Apache web server (apache2
) on Debian-based systems such as Ubuntu. It targets all hosts listed under the databases
group in your inventory.
---
- name: install Apache webserver
hosts: databases
tasks:
- name: install Apache webserver
apt:
name: apache2
State: latest
Use Service Module to Manage Services
The service module allows system administrators to start, stop, update, upgrade, and reload services on the system.
Example 1: Starting Apache Web Server
---
- name: Start service httpd, if not started
service:
name: httpd
state: started
Example 2: Stopping Apache Web Server
---
- name: Stop service httpd
service:
name: httpd
state: stopped
Example 3: Restarting a Network Interface enp2s0
---
- name: Restart network service for interface eth0
service:
name: network
state: restarted
args: enp2s0
Use Copy Module to Copy Files to Remote Locations
As the name suggests, the copy module copies files from one location on the remote machine to a different location on the same machine.