Getting Started with Ansible Playbooks
Ansible Playbooks are the core of Ansible's functionality, allowing you to define and execute tasks across your infrastructure. In this section, we'll explore the basics of creating and running Ansible Playbooks.
What are Ansible Playbooks?
Ansible Playbooks are YAML-based files that define the desired state of your infrastructure. They consist of one or more "plays," which are collections of "tasks" that Ansible will execute on the target hosts.
Creating an Ansible Playbook
Here's an example of a simple Ansible Playbook that installs the Apache web server on an Ubuntu 22.04 system:
- hosts: webservers
tasks:
- name: Install Apache
apt:
name: apache2
state: present
- name: Start Apache
service:
name: apache2
state: started
enabled: yes
In this Playbook:
hosts: webservers
specifies the target hosts for the play.
tasks:
defines the list of tasks to be executed.
- The first task installs the Apache web server using the
apt
module.
- The second task starts the Apache service and ensures it is enabled to start automatically on system boot.
Running an Ansible Playbook
To run the Ansible Playbook, you can use the following command:
ansible-playbook webserver.yml
This will execute the Playbook and apply the specified tasks to the target hosts.
Ansible Modules
Ansible provides a wide range of built-in modules that you can use to perform various tasks, such as managing packages, files, services, and more. You can find the complete list of available modules in the Ansible Module Index.
Ansible Roles
As your infrastructure grows, you can organize your Playbooks into reusable "roles" to promote modularity and maintainability. Roles allow you to encapsulate related tasks, variables, and files into a self-contained unit that can be easily shared and applied across multiple Playbooks.
By mastering the creation and execution of Ansible Playbooks, you can automate a wide range of tasks and streamline the management of your infrastructure.