Now that we know more about how Ansible works behind the scenes, let’s create our first Ansible Playbook! The examples in this section were performed on a Linux Distribution, though the steps should be nearly the same on most Operating Systems.
The first step in creating your first Ansible Playbook is to create a working directory to house it, and entering the directory:
$ mkdir my-playbook
$ cd my-playbook
We recommend that you use some type of version control software (VCS), though this is optional. For our example, we will use Git to track revision history:
$ git init
Initialized empty Git repository in /home/<user>/my-playbook/.git/
Creating an Ansible Inventory
Now we can start to define our inventory for this playbook. There are multiple strategies for managing an Ansible Inventory, though we’ll use a single static inventory file for simplicity. If you are managing an inventory that changes frequently, you may want to consider using a Dynamic Inventory instead.
Using your preferred text editor, create a file named ‘inventory’ in the ‘my-playbook‘ directory we created earlier and add the following:
# inventory.yml
lamp:
www1:
In the above example of an inventory file, we are deploying to a single host that we are referring to by its IP address or domain name.
Creating a Task
Create a site.yml file and put the following in it:
# site.yml
- hosts: all
tasks:
- name: Install packages
package:
name: '{{ packages }}'
state: present
Defining Variables
Ansible allows for configuring provided variables as well as defining your own. The following sources expand on the possible configuration options, as well as defining your own variables:
- Configuration Reference | ansible.com
- Using Variables | ansible.com
Group Variables (group_vars)
In the above example of a plaintext inventory, the hosts are within a group, one of which is ‘[webservers]’. If you have a need to define a common set of variables for any host that is in a certain group, you may assign variables by creating the ‘group_vars/’ directory, and within this directory you create the ‘webservers’ file:
# group_vars/webservers.yml
ansible_connection: /bin/python3
Host Variables (host_vars)
Following our example of an inventory file, not only can we set group-specific variables, though we can set host-specific variables. This allows for us to set additional variables for a specific host that compliment or modify the variables for the group the host is assigned to.
You may assign variables to hosts by creating the ‘host_vars/’ directory, and within this directory you create the ‘www1.example.com’ file:
# host_vars/www1.yml
ansible_host: domain.tld
ansible_user: my_user
Running your first playbook
$ ansible-playbook main.yml -i inventory