Skip to content

Instantly share code, notes, and snippets.

@jhoblitt
Created May 9, 2024 21:47
Show Gist options
  • Save jhoblitt/ba543c2fe17a8d66fbb6f251893011f9 to your computer and use it in GitHub Desktop.
Save jhoblitt/ba543c2fe17a8d66fbb6f251893011f9 to your computer and use it in GitHub Desktop.
Recursively extract the hostnames from an ansible inventory file and construct as prometheus sd file.
#!/bin/env ruby
require 'yaml'
require 'json'
inv = YAML.load_file('auto_inventory.yml')
def find_hosts(parent, h, output)
h.each {|k, v|
if v.is_a?(Hash)
find_hosts(k, v, output)
elsif k == 'ansible_host'
return output[parent] = v
end
}
return output
end
hosts = find_hosts(nil, inv, {})
file_sd_config = []
hosts.each {|k, v|
file_sd_config << {
'labels' => {
'__meta_hostname' => k,
'__meta_network_function' => '',
},
'targets' => [v],
}
}
puts JSON.pretty_generate(file_sd_config)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment