Skip to content

Instantly share code, notes, and snippets.

@tfhartmann
Created September 4, 2015 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tfhartmann/bd613becb83368abede1 to your computer and use it in GitHub Desktop.
Save tfhartmann/bd613becb83368abede1 to your computer and use it in GitHub Desktop.
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