Created
November 25, 2020 23:17
-
-
Save reidmv/cfa9f6ede58ec46dba57349ad1102150 to your computer and use it in GitHub Desktop.
Return list of nodes matching a named PE console node group
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
#!/opt/puppetlabs/puppet/bin/ruby | |
require 'json' | |
require 'net/http' | |
require 'etc' | |
def http(uri:, body: {}, request_class: Net::HTTP::Get) | |
token_file = File.join(Etc.getpwuid.dir, '.puppetlabs', 'token') | |
token = File.read(token_file) | |
parsed_uri = URI.parse(uri) | |
nethttp = Net::HTTP.new(parsed_uri.host, parsed_uri.port) | |
nethttp.use_ssl = true | |
nethttp.verify_mode = OpenSSL::SSL::VERIFY_NONE | |
request = request_class.new(parsed_uri.request_uri) | |
request['Content-Type'] = 'application/json' | |
request['X-Authentication'] = token | |
request.body = body.to_json | |
response = nethttp.request(request) | |
JSON.parse(response.body) | |
end | |
def and_group_rules(group, groups, rules = []) | |
if group['id'] == '00000000-0000-4000-8000-000000000000' | |
['and', *rules] | |
else | |
parent_group = groups.find { |g| g['id'] == group['parent'] } | |
and_group_rules(parent_group, groups, [group['rule'], *rules].compact) | |
end | |
end | |
def matching_nodes(group_id, groups) | |
group = groups.find { |g| g['id'] == group_id } | |
anded_rule = and_group_rules(group, groups) | |
pdbquery = http(uri: 'https://localhost:4433/classifier-api/v1/rules/translate', | |
body: anded_rule, | |
request_class: Net::HTTP::Post) | |
members = http(uri: 'http://localhost:8081/pdb/query/v4/nodes', | |
body: pdbquery, | |
request_class: Net::HTTP::Post) | |
rescue JSON::ParserError | |
# Unable to determine group members. Probably "all", doesn't have a rule. | |
[{'certname' => 'UNKNOWN'}] | |
end | |
groups = http(uri: 'https://localhost:4433/classifier-api/v1/groups') | |
unless group = groups.find { |g| g['name'] == ARGV[0] } | |
puts "Didn't find any group with the name #{ARGV[0]}" | |
exit 1 | |
end | |
puts matching_nodes(group['id'], groups).map { |n| n['certname'] } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment