Yep, that’s right, one more blog on cheatsheet. Because we can easily forget if we don’t practice continuously. From past few months I’ve been working on Ansible, I just want to make some notes on what I learned and try to update this cheatsheet frequently.
I have create example playbooks in my repo to cover below topics
Below are the things I choose to cover in this post. (Reader expected to have prior knowledge on Ansible)
- What is variable in ansible?
- How to define?
- Access variable
- ini and line configuration files
- line in file (GET/SET)
- ini (GET/SET)
- Poll a Command
- Jinja Templating
Variables or facts are created per hosts basis, since Ansible is designed to executes tasks on multiple servers, it maintains variables or facts per host.
For example, let’s say there is a group called ‘webservers’ in inventory file and defined a variable inside Play
All the variables that are defined in
vars are mapped to 3 web server, since we defined
webserver as target hosts. Ansible tracks the variables like below
|192.168.0.10||myvars, elements, atomic_no, atomic_weight|
|192.168.0.11||myvars, elements, atomic_no, atomic_weight|
|192.168.0.12||myvars, elements, atomic_no, atomic_weight|
And there are some other facts that are created by Ansible automatically like hostname, IPs, default gateway ,etc. Again these are also create per hosts basis.
Don’t try to use before the variable definition is complete like below
Remember, the variable
count will only defined after the execution of task
Creating or setting fact. The above playbook can written as
play’s variable/facts in another
As you know, a playbook contains one or more plays, each play contains one or more tasks. Generally, in Ansible, the variables in one play with different
hosts are not accessible directly on another play with another
hosts. By using
hostvars, we can access variables.
groups is in-built function to get list of hosts that are defined under
web_servers in inventory file. So, we are iterating on
web_servers and get host’s variable called “myvars” which was defined in above play.