Skip to content

Instantly share code, notes, and snippets.

@arbabnazar
Forked from halberom/extras.py
Created October 23, 2017 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arbabnazar/fe60137d7ca1e7de47117971ff7ca644 to your computer and use it in GitHub Desktop.
Save arbabnazar/fe60137d7ca1e7de47117971ff7ca644 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
# 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
#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
TASK [debug msg=[u'6', u'7']] ***************************************************
ok: [localhost] => {
"changed": false,
"msg": [
"6",
"7"
]
}
---
- 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) }}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment