Page
Ansible Playbook fundamentals
Ansible best practices are a good way to keep your automation content organized and manageable. In this lesson, we’ll cover some of Ansible’s key components and organize your content using best practice directory structures.
In this lesson, you will:
- Learn about playbook components.
- Learn about playbook directory structure.
Playbook directory structure
Although Ansible doesn’t enforce a specific directory structure, it’s recommended that you implement a best-practice directory layout to help organize and scale your Ansible playbook projects.
Below is a simplified example of a playbook project directory structure. For an official recommendation, please use the Ansible best practice documentation.
project-name/
├── inventory # Inventory files
│ ├── production.yml # Production servers inventory
│ └── staging.yml # Staging servers inventory
├── group_vars/ # Variables for groups
│ ├── web.yml # Variables for 'web' group
├── host_vars/ # Variables for specific hosts
│ ├── web1.yml # Variables for ‘web1’ node
│ └── web2.yml # Variables for 'web2' node
├── site.yml # Playbook site.yml'
└── files/ # Other files
│ ├── file1.txt
└── templates/ # Jinja2 templates
│ ├── index.html.j2
Example playbook directory structure.
Playbook components
Ansible playbooks consist of one or more plays that perform actions on target nodes. Let’s use an example to explain the key components of an Ansible playbook:
---
- name: Install and start Apache
hosts: web
become: true
tasks:
- name: Ensure the httpd package is installed
ansible.builtin.package:
name: httpd
state: present
- name: Start the httpd service if needed
ansible.builtin.service:
name: httpd
state: started
enabled: true
Ansible Playbook example.
Code | Definition |
| This playbook consists of one play called Install and Start Apache. |
| The target nodes to run the automation on. In our example we use the "web" inventory group. |
| A list of sequential actions you want to perform using Ansible modules. The first task name in the example is "Ensure the httpd package is installed". |
| Connection details to use privilege escalation on the target nodes. |
Your turn
Now to expand on the Ansible playbook example above:
- Open your editor and create an Ansible playbook file called
site.yml
. - Copy the content of the Ansible playbook example above into
site.yml
. - Create a new task with the name Start the
httpd
service if needed. - The task must start and enable the
httpd
service.
HINT: Refer to the ansible.builtin.service module documentation.
Your updated playbook should look similar to this:
---
- name: Install and start Apache
hosts: web
become: true
tasks:
- name: Ensure the httpd package is installed
ansible.builtin.package:
name: httpd
state: present
- name: Start the httpd service if needed
ansible.builtin.service:
name: httpd
state: started
enabled: true
Updated Ansible playbook example.