Skip to content

Instantly share code, notes, and snippets.

@icy
Created February 12, 2020 09:36
Show Gist options
  • Save icy/bcc869eb63f1837470254f50ce178ea0 to your computer and use it in GitHub Desktop.
Save icy/bcc869eb63f1837470254f50ce178ea0 to your computer and use it in GitHub Desktop.
k8s-selector.rb
#!/usr/bin/env ruby
# Purpose : Select the objects you want from maninfests,
# as you may not want to deploy everything.
# Author : Ky-Anh Huynh
# Date : 2019-12
# Example :
#
# helm foo | k8s-select kind=Ingress | kubectl diff -f-
# helm foo | k8s-select metadata.name=someth | kubectl diff -f-
#
require 'yaml'
class NilClass
def dig(st)
return nil
end
end
def doc_query(doc,query)
key = ""
val = doc
query.split(".").each do |k|
key = "#{key}.#{k}"
if gs = k.to_s.match("\[([0-9]+)\]")
val = val.is_a?(Array) ? val[gs[1].to_i] : nil
else
val = val.dig(k)
end
end
return val ? val.downcase : nil
end
def match_argv_doc(args,doc)
args.select{|s| s.include?("=")}.detect do |arg|
query,value = arg.split("=", 2)
query_value = doc_query(doc, query)
query_value.nil? ? nil: query_value.match(value.downcase)
end
end
docs = YAML.load_stream(STDIN)
docs.each do |doc|
next if doc.nil? or doc.empty?
if match_argv_doc(ARGV,doc)
puts YAML.dump(doc)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment