Ansible variables and include_role
Introduction
Ansible is simple open source IT engine which automates application deployment, intra service orchestration, cloud provisioning and many other IT tools.
Ansible is easy to deploy because it does not use any agents or custom security infrastructure.
Ansible uses playbook to describe automation jobs, and playbook uses very simple language i.e. YAML (It’s a human-readable data serialization language & is commonly used for configuration files, but could be used in many applications where data is being stored).
Prerequisites
To follow along with this tutorial, you will need to install and configure Ansible so that you can create and run playbooks. You will also need to understand how to write Ansible playbooks.
Ansible Variables
A variable, just like in many programming languages, is essentially a key that represents a value. It helps you to use and assign a value to a variable and use that anywhere in the playbook.
Let’s take a look a few examples of valid and unacceptable variable names:
Valid Variable Name Examples:
football
foot_ball
football20
foot_ball20
Non-valid Variable Name Examples:
foot ball
20
foot-ball
Playbook variables are quite easy and straightforward. To define a variable in a playbook, simply use the keyword vars before writing your variables with indentation.
To access the value of the variable, place it between the double curly braces enclosed with quotation marks.
Here’s a simple playbook example:
- hosts: all
vars:
greeting: Hello world! tasks:
- name: Ansible Basic Variable Example
debug:
msg: "{{ greeting }}"
In the above playbook, the greeting variable is substituted by the value Hello world! when the playbook is run. The playbook simply prints the message Hello world! when executed.
Sometimes you want yo use a variable across multiple roles. Unfortunately ansible doesn’t have really a concept of global vars, but there is a trick!
You can define group variables for ALL groups, that is indeed like a global variable.
Assume the below structure:
.
├── group_vars
│ └── all #It contains variable myVar: "Welcome"
└── test.yml
And you can access and test the variable from group_vars/all like this:
#test.yml- hosts: localhosttasks:
- name: Variable test
debug:
msg: "{{ myVar }}" #myVar variable stored in group_vars/all.
And when you run this “test.yml” it will show the value of “myVar”:
PLAY [localhost] ***************************************************TASK [Gathering Facts] *********************************************
ok: [localhost]TASK [Variable test]************************************************
ok: [localhost] => {
"msg": "Welcome"
}PLAY RECAP *********************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
You can set multiple variables with the same name in many different places. When you do this, Ansible loads every possible variable it finds, then chooses the variable to apply based on variable precedence. In other words, the different variables will override each other in a certain order.
Have a look at the Variable Precedence: Where Should I Put A Variable? chapter.
Ansible include_role
It Dynamically loads and executes a specified role as a task. Task-level keywords, loops, and conditionals apply only to the include_role
statement itself.
It has different parameters but we will learn about-
- tasks_from: File to load from a role’s
tasks/
directory.
By using tasks_from, you can call common tasks which needs everytime while executing different playbooks.
For Example: If you want to create 5 UUIDs then you dont’t need to create 5 uuid by separating 5 different tasks. For that you can simply create one common task and by using loop you can create 5 UUIDs by iterating over it.
Let’s execute this example using include_role:
#Create Directory structure:common
├── ./tasks
│ └── createUUID.yml
└── main.yml
Write task to create 5 UUID:
#./common/tasks/createUUID.yml- name: Generate UUIDs.
shell: "/usr/bin/uuid"
loop: "{{ range(0, numUUID) | list }}"
register: uuids- name: Create list of uuids.
set_fact:
totalUUID: "{{ totalUUID | default([]) + [uuids['results'][item]['stdout']] }}"
loop: "{{ range(0, uuids['results'] | length) | list }}"- debug:
msg: "Display the UUIDs: {{ totalUUID }}"
Call this common task into main.yml
#main.yml- name: Create UUID
hosts: localhost
connection: localtasks:
- name: Set required number of uuids.
include_role:
name: common
tasks_from: createUUID
vars:
numUUID: 5
When you execute “main.yml” then it will print the 5 UUIDs on your console.
Conclusion
This brings us to the end of this tutorial on working with Ansible variables and built in include_role. Roles allow you to easily reuse and share code, and to implement your changes in controlled and modular fashion. Also, the reusability of these group variables makes it more relevant to use in a production environment.
Hope this helps! :)