Skip to content

Instantly share code, notes, and snippets.

@cespare
Created October 28, 2013 04:17
Show Gist options
  • Save cespare/7191373 to your computer and use it in GitHub Desktop.
Save cespare/7191373 to your computer and use it in GitHub Desktop.
Ansible host reverse lookup script
#!/usr/bin/env ruby
version_parts = RUBY_VERSION.split(".").map(&:to_i)
if version_parts[0] < 2 && version_parts[1] < 9
abort "Ruby >= 1.9 required."
end
require "set"
if ARGV.size != 1
puts <<EOF
Usage:
$ ansible-lookup SEARCH_TERM
where SEARCH_TERM is partial string query that matches some hostname.
EOF
exit 1
end
search_term = ARGV[0]
host_file = ENV["ANSIBLE_HOSTS"]
abort "No ANSIBLE_HOSTS set." if host_file.empty?
groups = Set.new
File.open(host_file).each do |line|
if line =~ /^\[([^\]]+)\]/
groups << $1.split(":")[0]
end
end
# Dictionary of pid, output, status keyed by group.
results = {}
groups.each do |group|
rerr, werr = IO.pipe
rout, wout = IO.pipe
results[group] = {
:pid => Kernel.spawn("ansible", group, "--list-hosts", :err => werr, :out => wout),
:rerr => rerr, :werr => werr,
:rout => rout, :wout => wout,
}
end
puts "Ansible groups matching '#{search_term}':"
results.each do |group, result|
_, status = Process.wait2(result[:pid])
result[:werr].close
result[:wout].close
if status != 0
puts "Ansible error (exit status #{status}):"
puts result[:rout].read
puts result[:rerr].read
exit 1
end
if result[:rout].readlines.any? { |line| line[search_term] }
puts group
end
result[:rerr].close
result[:rout].close
end
@raags
Copy link

raags commented Aug 25, 2015

The groups a host is part of is available via the "group_names" host fact :

---
- name: test playbook2
  hosts: "{{cli_hosts}}"
  gather_facts: no
  tasks:
    - debug: var=group_names

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment