Last active
July 26, 2019 09:00
-
-
Save halberom/4670d3c114b7ff020f02 to your computer and use it in GitHub Desktop.
ansible - example of nasty custom jinja filter to get attribute from all hosts in a group
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ansible_plugins/filter_plugins/extras.py | |
def getFromDict(dataDict, mapList): | |
return reduce(lambda d, k: d[k], mapList, dataDict) | |
def get_host_attr_for_group(hosts, hostvars, keys): | |
# given a list of nested keys, return the value for each host in hostvars | |
results = [] | |
for host in hosts: | |
results.append(getFromDict(hostvars[host], keys)) | |
return results |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#vagrant ansible_ssh_port=2222 ansible_ssh_host=127.0.0.1 | |
centos66 ansible_ssh_host=192.168.35.21 ansible_ssh_private_key=~/.vagrant/insecure_private_key | |
centos70 ansible_ssh_host=192.168.35.22 ansible_ssh_private_key=~/.vagrant/insecure_private_key | |
[centos] | |
centos66 | |
centos70 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
TASK [debug msg=[u'6', u'7']] *************************************************** | |
ok: [localhost] => { | |
"changed": false, | |
"msg": [ | |
"6", | |
"7" | |
] | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
- hosts: centos | |
remote_user: vagrant | |
tasks: | |
- hosts: localhost | |
remote_user: vagrant | |
gather_facts: false | |
vars: | |
keys: | |
# - ansible_default_ipv4 | |
# - address | |
- ansible_distribution_major_version | |
tasks: | |
- debug: msg="{{ groups['centos'] | get_host_attr_for_group(hostvars, keys) }}" |
the extract
filter didn't exist when I created this example
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What about
groups['centos'] | map('extract', hostvars, 'ansible_distribution_major_version') | list
? (Taken from Ansible's documentation https://docs.ansible.com/ansible/2.5/user_guide/playbooks_filters.html#extract-filter)