In [ ]:
cd /notebooks/exercise-03
In [ ]:
# Let's run the setup module
!ansible -i inventory -m setup localhost
In [ ]:
!ansible >/dev/null -i inventory -m setup localhost --tree host_status
In [ ]:
# Solution
!tree host_status
import json
ret = json.load(open('host_status/localhost'))
f = ret['ansible_facts'] # .keys()
f['ansible_all_ipv4_addresses']
In [ ]:
# use this cell for the exercise
In [ ]:
!ansible-playbook get-facts.yml
Ansible can create files using the jinja2 template engine.
Filters are jinja2 functions to process facts and variables.
Here's a template example
<html>
<body>
# template.j2
This is a static line while the following one
expands the ansible_hostname variable {{ansible_hostname}}
Now we process a simple number {{ 3.1415 | int }}
Or take the first letter from a variable: {{ ansible_hostname[0] }}
</body>
</html>
You can process entries inside a template with filters.
In [ ]:
# Use the debug module to process a variable
# Modify the command to print the last two letters.
!ansible localhost -mdebug -a"var=ansible_user[:2]"
In [ ]:
!cat vars-and-facts.yml
In [ ]:
# This playbook mixes variables and facts
!ansible-playbook vars-and-facts.yml --tags variables
Inside {{ braces }} you can process expressions using filters.
- debug:
msg: >
Floor it {{ ( one + pi ) | int }}
A simple filter using debug
in a playbook.
- name: We already found a simple filter mapping entries to int
debug: msg="{{ 3.1415 | int }}"
A filter is essentially a function returning a function, like a lambda.
int_filter = lambda x: int(x)
A more complex filter:
- name: This is a getter
debug:
msg: >
{{ ['host1', 'host2'] |
map('extract', hostvars, ['key1', .. , 'keyN'])
}}
where
hostvars_getter = lambda host: hostvars[host]['key1'][..]['keyN']
You can pipeline filters and test them incrementally.
We'll see further examples when processing hostvars
In [ ]:
# This playbook mixes variables and facts
!ansible-playbook vars-and-facts.yml --tags filters
Edit the last section of vars-and-facts.yml so that it shows:
- the free percentage of every device
Hints:
- use the playbook as a reference
- iterate thru server facts
In [ ]:
!ansible-playbook vars-and-facts.yml --tags exercise
In [ ]: