Ansible playbooks are YAML files that define a series of tasks to be executed on specified hosts. They are the primary way to automate tasks in Ansible. Here's how they work:
Structure: A playbook consists of one or more "plays." Each play targets a group of hosts and defines the tasks to be executed on those hosts.
Hosts: You specify which hosts the playbook will run on, typically defined in an inventory file.
Tasks: Each play contains a list of tasks. Tasks use Ansible modules to perform actions, such as installing packages, copying files, or managing services.
Variables: You can define and use variables within playbooks to make them more dynamic and reusable. Variables are referenced using the
{{ variable_name }}syntax.Execution: When you run a playbook, Ansible connects to the specified hosts and executes the tasks in the order they are defined.
Example Playbook
Here's a simple example of an Ansible playbook:
- hosts: webservers
tasks:
- name: Install Apache
yum:
name: httpd
state: present
- name: Start Apache service
service:
name: httpd
state: started
In this example:
- The play targets hosts in the
webserversgroup. - It installs the Apache web server and ensures the service is started.
For more hands-on practice, consider exploring LabEx labs focused on writing and executing Ansible playbooks!
