Instantly share code, notes, and snippets.

Embed
What would you like to do?
me hacking around with ansible_spec and ruby
#!/bin/env ruby
require 'hostlist_expression'
#
def parse_inventory_file (filecontent)
group_map = {}
group_map.default = []
group = []
g = Array.new
#parse the name of the group, and all hosts in it
filecontent.each_line{|line|
line = line.chomp
if line.start_with?('#') #comment
next
end
if line.empty? == true #null
next
end
if line.start_with?('[') && line.end_with?(']')
group = line.gsub('[','').gsub(']','')
elsif line.split.count == 1 && line.include?("[") && line.include?("]")
hostlist_expression(line,":").each{|host|
g = g.push(group) unless g.include?(group)
group_map[host] = g
}
else
host = line
group_map[host] = group_map[host].push(group)
end
}
return group_map
end
expected_input1 = <<-EOF
[group1]
clarinet001-135
EOF
expected_output1 = { 'clarinet001-135' => ['group1'] }
expected_input2 = <<-EOF
[group1]
clarinet001-[135:137]
EOF
expected_output2 = { 'clarinet001-135' => ['group1'], 'clarinet001-136' => ['group1'], 'clarinet001-137' => ['group1'] }
expected_input3 = <<-EOF
[group1]
clarinet001-135
[group2]
clarinet001-135
EOF
expected_output3 = { 'clarinet001-135' => ['group1', 'group2'] }
## Tests
## Test Hosts/Groups
actual_output1 = parse_inventory_file(expected_input1)
if actual_output1 == expected_output1
puts 'Passed'
else
puts "Failed expected #{expected_output1} got #{actual_output1}"
end
## Test ranges
actual_output2 = parse_inventory_file(expected_input2)
if actual_output2 == expected_output2
puts 'Passed'
else
puts "Failed I expected: \n #{expected_output2} \nI got: \n #{actual_output2}"
end
## Test server that has multiple groups
actual_output3 = parse_inventory_file(expected_input3)
if actual_output3 == expected_output3
puts 'Passed'
else
puts "Failed I expected: \n #{expected_output3} \nI got: \n #{actual_output3}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment