Skip to content

Instantly share code, notes, and snippets.

@IanVaughan
Created September 4, 2018 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IanVaughan/732c5a778a0e32306894a516bd565bef to your computer and use it in GitHub Desktop.
Save IanVaughan/732c5a778a0e32306894a516bd565bef to your computer and use it in GitHub Desktop.
Script to get logs or a console into k8s pods
# gem install tty-prompt
# gem install tty-command
require 'tty-prompt'
require 'tty-command'
require 'thor'
require 'pry'
class MyCLI < Thor
class_option :env, type: :string, default: ENV['K8S_ENV']
class_option :app, type: :string, default: ENV['K8S_APP']
class_option :run, type: :string, default: ENV['K8S_RUN']
desc "console", "Get a console"
def console()
if !options.key("run") && options["run"].nil?
puts "Unknown run type, need to know if its rails or elixir\n Use --run=RUN\n Or set env K8S_RUN=RUN"
exit(-1)
end
[:console, options]
end
desc "logs", "Show logs"
def logs()
[:logs, options]
end
end
command, _options = MyCLI.start(ARGV)
options = _options.dup # to unfreeze Thor returned object
options ||= {}
if !options.key("env") && options["env"].nil?
prompt = TTY::Prompt.new
options["env"] = prompt.select("ENV", %w(qa staging prod))
end
if !options.key("app") && options["app"].nil?
puts "Unknown app\n Use --app=APP\n Or set env K8S_APP=APP"
exit(-1)
end
puts "* Finding #{options["app"]} pods on #{options["env"]}..."
# Get a list of pods on given ENV matching given APP
cmd = TTY::Command.new(printer: :null)
kubectl = "kubectl --context #{options["env"]} get pods | grep #{options["app"]}"
result, _err = cmd.run(kubectl)
# Extract pod names from kubectl result
pods = result.split.each_slice(5).map { |a| a[0] }
prompt = TTY::Prompt.new
pod = prompt.select("Which pod", pods)
def get_pod_command(run)
case run
when "rails"
"rails console"
when "elixir"
"./bin/rex remote_console"
end
end
def get_command(command, env, pod, run)
case command
when :logs
"kubectl --context #{env} logs -f #{pod}"
when :console
"kubectl --context #{env} exec -it #{pod} #{get_pod_command(run)}"
end
end
run_cmd = get_command(command, options["env"], pod, options["run"])
puts "* Performing : #{run_cmd}"
exec(run_cmd)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment