ansible/scripts/hosts_with_var_set

77 lines
2.2 KiB
Text
Raw Normal View History

#!/usr/bin/python
2015-11-18 04:00:07 +00:00
# doteast; base from skvidal's freezelist
2016-02-09 18:24:50 +00:00
# doteast porting to ansible 2.0
2015-11-18 04:00:07 +00:00
# list hosts with ansible var[=value], Or
2016-02-09 18:24:50 +00:00
# list all hosts with their corresponding vars
# Note that the script will attempt to "match" the supplied value of the var against the values if it the var is multivalued
2016-02-09 18:24:50 +00:00
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
import sys
from optparse import OptionParser
parser = OptionParser(version="1.0")
parser.add_option('-i', dest='inventory', default=None,
help="Path to inventory file/dir")
parser.add_option('-o', dest='variable', default=None,
help="variable name to check")
2015-11-18 04:00:07 +00:00
parser.add_option('-a', action="store_true", dest='all_vars', default=None,
help="get all vars")
opts, args = parser.parse_args(sys.argv[1:])
2015-11-18 04:00:07 +00:00
if ((opts.variable == None and opts.all_vars == None) or (opts.variable != None and opts.all_vars != None)):
print "Usage: hosts_with_var_set -o varname[=value] | -a"
sys.exit(-1)
2016-02-09 18:24:50 +00:00
variable_manager = VariableManager()
loader = DataLoader()
if opts.inventory:
inv = Inventory(loader=loader,variable_manager=variable_manager, host_list=opts.inventory)
else:
inv = Inventory(loader=loader,variable_manager=variable_manager)
variable_manager.set_inventory(inv)
2015-11-18 04:00:07 +00:00
matching=True
2016-02-09 18:24:50 +00:00
2015-11-18 04:00:07 +00:00
if opts.variable != None:
if opts.variable.find("=") == -1:
matching=False
var_name=opts.variable
else:
var_name,value = opts.variable.split('=')
if value == "":
value="None"
var_set = []
for host in sorted(inv.get_hosts()):
2016-02-09 18:24:50 +00:00
vars = variable_manager.get_vars(loader=loader, host=host)
2015-11-18 04:00:07 +00:00
if opts.variable == None:
2016-02-09 18:24:50 +00:00
# remove expanded 'all' groups
vars.pop('groups')
vars['groups']=host.get_groups()
print "%s\n%s\n" % (host.get_name(),vars)
2015-11-18 04:00:07 +00:00
else:
2016-02-09 18:24:50 +00:00
if vars.has_key(var_name):
2015-11-18 04:00:07 +00:00
if not matching:
2016-02-09 18:24:50 +00:00
var_set.append(host.get_name())
2015-11-18 04:00:07 +00:00
else:
if str(vars.get(var_name)).find(value) != -1:
2016-02-09 18:24:50 +00:00
var_set.append(host.get_name())
2015-11-18 04:00:07 +00:00
if opts.variable != None:
if not matching:
print 'hosts with variable %s:' % var_name
else:
print 'hosts with variable %s matching %s value' % (var_name,value)
for host in sorted(var_set):
print host