A playbook in Ansible is a YAML file that contains a collection of tasks, organized in a structured manner, to automate a specific set of actions on remote hosts. Playbooks are at the heart of Ansible and provide a way to define the desired state of your infrastructure and orchestrate various tasks to achieve that state.
A playbook consists of one or more plays, and each play contains a set of tasks to be executed on a specific set of hosts or groups defined in the inventory. Within each task, you define a module to perform a specific action, such as running a command, copying files, managing services, or interacting with cloud providers.
Here's an example of a simple playbook that installs and starts an Apache web server on a group of remote hosts:
---
- name: Install and Start Apache
hosts: webservers
become: true
tasks:
- name: Install Apache package
package:
name: apache2
state: present
- name: Start Apache service
service:
name: apache2
state: started
In this playbook:
- `name` provides a descriptive name for the play.
- `hosts` specifies the target hosts or group(s) from the inventory on which the play will be executed.
- `become: true` indicates that the tasks will be executed with escalated privileges (e.g., using sudo).
- `tasks` define a list of individual tasks to be executed sequentially.
The tasks in this example use the `package` module to install the Apache package and the `service` module to start the Apache service.
You can run a playbook using the `ansible-playbook` command, passing the playbook file as an argument. Ansible will connect to the target hosts, execute the tasks defined in the playbook, and ensure the desired state is achieved on the infrastructure.