Skip to content

Instantly share code, notes, and snippets.

@evantahler
Last active August 29, 2015 14:14
Show Gist options
  • Save evantahler/81223be0f7ff326db8ad to your computer and use it in GitHub Desktop.
Save evantahler/81223be0f7ff326db8ad to your computer and use it in GitHub Desktop.
If you want ansible tower to source an inventory file checked into a project, here's an example of how to do it.
#!/usr/bin/env ruby
require 'json'
inventory_file = 'production'
# Configure inputs
# assumes a project layout with ./inventories/{{ inventory_file }}
if File.exists? '/var/lib/awx/projects/'
folder = Dir.glob('/var/lib/awx/projects/*').max { |a,b| File.ctime(a) <=> File.ctime(b) }
path = folder + '/inventories/' + inventory_file
else
path = File.dirname(__FILE__) + '/../inventories/' + inventory_file
end
lines = File.read( path ).split("\n")
current_section = nil
data = {
"_meta" => {
"hostvars" => {}
}
}
# Parse the inventory file
lines.each do |line|
parts = line.split(' ')
next if parts.length == 0
next if parts.first[0] == "#"
next if parts.first[0] == "/"
if parts.first[0] == '['
current_section = parts.first.gsub('[','').gsub(']','')
next
end
name = parts.shift
d = {}
while parts.length > 0
part = parts.shift
words = part.split('=')
d[words.first] = words.last if words.first != 'ansible_ssh_user'
end
if current_section.nil?
data["_meta"]["hostvars"][name] = d
else
data[current_section] = [] if data[current_section].nil?
data[current_section].push name
end
end
puts JSON.pretty_generate( data )
#!/usr/bin/env ruby
require 'json'
inventory_file = 'staging'
# Configure inputs
# assumes a project layout with ./inventories/{{ inventory_file }}
if File.exists? '/var/lib/awx/projects/'
folder = Dir.glob('/var/lib/awx/projects/*').max { |a,b| File.ctime(a) <=> File.ctime(b) }
path = folder + '/inventories/' + inventory_file
else
path = File.dirname(__FILE__) + '/../inventories/' + inventory_file
end
lines = File.read( path ).split("\n")
current_section = nil
data = {
"_meta" => {
"hostvars" => {}
}
}
# Parse the inventory file
lines.each do |line|
parts = line.split(' ')
next if parts.length == 0
next if parts.first[0] == "#"
next if parts.first[0] == "/"
if parts.first[0] == '['
current_section = parts.first.gsub('[','').gsub(']','')
next
end
name = parts.shift
d = {}
while parts.length > 0
part = parts.shift
words = part.split('=')
d[words.first] = words.last if words.first != 'ansible_ssh_user'
end
if current_section.nil?
data["_meta"]["hostvars"][name] = d
else
data[current_section] = [] if data[current_section].nil?
data[current_section].push name
end
end
puts JSON.pretty_generate( data )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment