Last active
June 3, 2019 13:45
-
-
Save sebastian-palma/c49a3edecb05ec5ece55b920f777605a to your computer and use it in GitHub Desktop.
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
# frozen_string_literal: true | |
require 'open3' | |
require 'pry' | |
module Utils | |
class GemVerifier | |
def check_needed_gems | |
require 'tty-prompt' | |
rescue LoadError | |
system('gem install tty-prompt > /dev/null') | |
Gem.clear_paths | |
require 'tty-prompt' | |
end | |
end | |
end | |
class PromptApplication | |
def prompt | |
@prompt ||= TTY::Prompt.new | |
end | |
def select(message, collection, options) | |
prompt.select(message, collection, options.merge(filter: true)) | |
end | |
end | |
class ContextExecutor < PromptApplication | |
COMMAND = 'kubectl config get-contexts -o name' | |
private_constant :COMMAND | |
def context_selection | |
lambda do |selection| | |
contexts.find { |context| context[:name] == selection }[:fullname] | |
end.call(select('Select a context', context_names, per_page: contexts.size)) | |
end | |
private | |
def context_names | |
contexts.map { |context| context[:name] } | |
end | |
def contexts | |
@contexts ||= raw_contexts.split("\n").map do |context| | |
{ name: context[/\/(.*)$/, 1], fullname: context } | |
end | |
end | |
def raw_contexts | |
Open3.capture3(COMMAND).first | |
end | |
end | |
class PodsExecutor < PromptApplication | |
COMMAND = 'kubectl get pods' | |
POD_DATA = %i[name ready status restarts age].freeze | |
RAILS_CONSOLE = 'RAILS_ENV=production bundle exec rails c' | |
private_constant :COMMAND, :POD_DATA, :RAILS_CONSOLE | |
def enter_to_pod | |
system("kubectl config use-context #{ContextExecutor.new.context_selection} > /dev/null") | |
pod = pod_selection | |
open_console = prompt.yes?('Open the application console?') | |
system("kubectl exec -it #{pod} bash") unless open_console | |
system("kubectl exec -it #{pod} -- bash -c '#{RAILS_CONSOLE}'") | |
rescue NoMethodError | |
puts "error: the server doesn't have a resource type \"pods\"" | |
end | |
private | |
def pod_selection | |
select('Select a pod', pod_names, per_page: pods.size) | |
end | |
def pod_names | |
pods.filter { |pod| pod[:status] == 'Running' }.map { |pod| pod[:name] } | |
end | |
def pods | |
@pods ||= pods_output.split("\n")[1..-1].map(&:split).map { |line| POD_DATA.zip(line).to_h } | |
end | |
def pods_output | |
Open3.capture3(COMMAND).first | |
end | |
end | |
Utils::GemVerifier.new.check_needed_gems | |
PodsExecutor.new.enter_to_pod |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment