Skip to content

Instantly share code, notes, and snippets.

@halberom
Last active July 26, 2019 09:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save halberom/4670d3c114b7ff020f02 to your computer and use it in GitHub Desktop.
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
# 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) }}"
@paulRbr
Copy link

paulRbr commented Dec 20, 2018

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)

@halberom
Copy link
Author

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