Table of Content
- Introduction
- Multiple tasks in Single Playbook.
- Playbook Execution
- Include Tasks in Playbook.
- Use Variable inside the Playbook
- Include variable file inside the playbook
Introduction
The playbook is the main program, all the code is written here, it is also known as a tasks file. It can contain one or multiple tasks. It is written in the YAML language. Visit www.yamllint.com/ to learn and validate your scripts.
This file is like the main() function of our program.
It looks something like below.
![]() |
PlayBook Structure |
Example,
---
- name: Collect IOS Device Facts
connection: network_cli
gather_facts: True
hosts: all
tasks:
- name: show output
debug:
var: ansible_facts
...
This playbook gathers information about all devices provided in the inventory using single task.
Our directory structure looks like below.
- It is a basic structure of files that is required every time. There are more files, which is discussed later.
Output: It contains all the information of the connected node.
Eg,
---
name: Check web servers
hosts: webservers
remote_user: root
tasks:
- name: Ensure apache is at the latest version
yum:
name: httpd
state: latest
- name: Ensure that postgresql is started
service:
name: postgresql
state: started
...
Description:
Name: It is used for the naming convention and easy readability for the tasks, It does not affect anything if not written.
Hosts: It states the file is only executed to specific users/groups of the inventory file. Here, in our case it is webservers.Tasks: Contain a list of plays and configurations to perform.
"There are many other different fields in the playbook which is discussed in a later part."
Playbook execution
It is also called ad-hoc commands.
ansible-playbook playbook_file.yml
By default, our inventory file is in "etc/ansible/hosts". But when we access it from a different location or change its default name we need to let it know to ansible.
There are two ways,
1. Update the ansible.cfg file.
2. Pass file location during execution. Example below.
ansible-playbook -i hosts playbook_file.yml
Include tasks in playbooks.
"Make Sure every time you write any file follow the YAML Structure"
E.g
![]() |
Include Playbook files. |
Use Variable Inside Playbook.
---
- name: Working with Variable in Ansible
hosts: localhost
vars:
- name: Karan Joshi
company: Itblizz
tasks:
- name: Print the Variables
debug:
msg: "Name :{{ name }}({{ company }})"
...
Output:
Include Variable File in Playbook.
For better visibility, we use separate files. To include variables inside the playbook we use the vars_files attribute below the hosts.
Syntax,
- name: include variable File hosts: all vars_files: - /vars/external_vars.yml