Created
May 9, 2024 21:47
-
-
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.
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
#!/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