Creating your first Ansible Playbook
Introduction
In this article, we will be creating our very first Ansible Playbook. But first, let's understand what an Ansible Playbook is. Playbooks are Ansible’s configuration, deployment, and orchestration language. They can describe a policy you want your remote systems to enforce, or a set of steps in a general IT process.
Prerequisites
Before we begin, ensure that you have Ansible installed on your machine. If you are new to Ansible, refer to the official Ansible Installation Guide for detailed instructions.
Understanding Ansible Playbooks
Ansible Playbooks are written in YAML format. They begin with three hyphens ---
and end with three dots ...
. Each playbook is composed of one or more 'plays' in a list.
A 'play' is essentially a set of tasks that runs on one, or more, hosts. Tasks are executed in order, one at a time, against all machines matched by the host pattern, before moving on to the next task.
Creating Our First Playbook
Let's create a simple Ansible Playbook. We'll write a playbook that installs Apache HTTP Server on a remote host.
Create a new file called install_apache.yml
and open it with your favourite text editor.
---
- name: Install Apache
hosts: webservers
become: yes
tasks:
- name: Ensure Apache is at the latest version
apt:
name: apache2
state: latest
...
Here's what each line does:
name: Install Apache
- This is the name of our play.hosts: webservers
- This tells Ansible that the play should run on the hosts group named 'webservers'.become: yes
- This instructs Ansible to use sudo to elevate privileges.tasks:
- This starts the list of tasks. Tasks are the things you want Ansible to do.- The final four lines starting with
- name: Ensure Apache...
is our task. It makes sure that the Apache HTTP Server is installed and up to date.
Running the Playbook
To execute the playbook, we use the ansible-playbook
command followed by the name of the file. Ensure you run this command from the same directory where the playbook file is located.
ansible-playbook install_apache.yml
This command will run the playbook against the hosts specified in the 'webservers' group.
Conclusion
Congratulations! You have successfully created and run your first Ansible Playbook. Remember, this is just the tip of the iceberg. Ansible's power and flexibility allow you to manage and configure complex multi-tier applications. So, keep practicing and exploring more about Ansible Playbooks.