Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jctanner
Last active February 12, 2018 20:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jctanner/357c8c54ef0c884eef6d0aba3c54d979 to your computer and use it in GitHub Desktop.
Save jctanner/357c8c54ef0c884eef6d0aba3c54d979 to your computer and use it in GitHub Desktop.
findvar filter plugin
PLAYBOOK: site.yml *******************************************************************************
1 plays in site.yml
PLAY [all] ***************************************************************************************
META: ran handlers
TASK [debug] *************************************************************************************
task path: /home/jtanner/workspace/issues/AP-HOSTVAR_LOOKUP/site.yml:5
ok: [el6host] => {
"failed": false,
"msg": "YOU FOUND ME!"
}
ok: [testhost] => {
"failed": false,
"msg": "YOU FOUND ME!"
}
ok: [el7host] => {
"failed": false,
"msg": "YOU FOUND ME!"
}
TASK [debug] *************************************************************************************
task path: /home/jtanner/workspace/issues/AP-HOSTVAR_LOOKUP/site.yml:7
ok: [el7host] => {
"failed": false,
"msg": "not found"
}
ok: [el6host] => {
"failed": false,
"msg": "not found"
}
ok: [testhost] => {
"failed": false,
"msg": "not found"
}
#!/usr/bin/env python
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.errors import AnsibleFilterError
from ansible.errors import AnsibleUndefinedVariable
from jinja2.runtime import Undefined
def var_find(vars, varname):
"""Iterate hosts and find the var"""
for k, v in vars.items():
for k2, v2 in v.items():
if k2 == varname:
return v2
return Undefined()
class FilterModule(object):
def filters(self):
return {
'findvar': var_find
}
el6host
el7host findme="YOU FOUND ME!"
testhost
- hosts: all
connection: local
gather_facts: False
tasks:
- debug:
msg: "{{ hostvars|findvar('findme') }}"
- debug:
msg: "{{ hostvars|findvar('badvarname')|default('not found') }}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment