Skip to content

Instantly share code, notes, and snippets.

@pranny
Created June 29, 2016 07:51
Show Gist options
  • Save pranny/6f1651095cf99fa00ef68cfc6f8d887c to your computer and use it in GitHub Desktop.
Save pranny/6f1651095cf99fa00ef68cfc6f8d887c to your computer and use it in GitHub Desktop.
Ruby script to parse ansible host file into hash
# The ansible hosts file parser class
class AnsibleHostsFileParser
HOST_NAME_REGEX = /^\[(.*)\]$/
IP_ADDR_REGEX = /^((?:[0-9]){1,3}\.){1,3}[0-9]{1,3}$/
def self.load_hosts(hostsfile)
f = File.open(hostsfile)
t = f.read
f.close
parse_ansible_hosts_info(t)
end
# Parses ansible file contents
# @param [String] hosts_file The location of the host file
# @return [Hash{ String => List }] A hash containing hostnames as the key
# and the list of IP address as the value
def parse_ansible_hosts_info(text)
hostname = nil
text.split(/\n+/).inject({}) do |hosts, el|
if el.match HOST_NAME_REGEX
hostname = el.match(HOST_NAME_REGEX)[1]
unless hosts.has_key?hostname
hosts[hostname] = Array.new
end
elsif el.match IP_ADDR_REGEX
ip_addr = el.match(IP_ADDR_REGEX)[0]
hosts[hostname] = hosts[hostname].push(ip_addr)
end
hosts
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment