Created
June 29, 2016 07:51
-
-
Save pranny/6f1651095cf99fa00ef68cfc6f8d887c to your computer and use it in GitHub Desktop.
Ruby script to parse ansible host file into hash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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