Skip to content

Instantly share code, notes, and snippets.

@thadeu
Last active March 21, 2026 01:28
Show Gist options
  • Select an option

  • Save thadeu/c9ec24c2e1b4a8ef7f90f5dfb1b46843 to your computer and use it in GitHub Desktop.

Select an option

Save thadeu/c9ec24c2e1b4a8ef7f90f5dfb1b46843 to your computer and use it in GitHub Desktop.
Config k8s
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'optparse'
require 'json'
require 'base64'
class KubernetesConfig
def self.run!
new.run
end
attr_reader :namespace, :configmap_name, :secret_name
def initialize
@namespace = ENV['NAMESPACE'] || 'default'
@configmap_name = ENV['CONFIGMAP_NAME'] || 'atendesimples-ws-conf'
@secret_name = ENV['SECRET_NAME'] || 'atendesimples-ws-secrets'
end
def run
parse_options
execute_command
end
private
def parse_options
OptionParser.new do |opts|
opts.banner = "Uso: #{$0} [comando] [opções] [argumentos...]"
opts.on('-n', '--namespace NAMESPACE', 'Namespace do Kubernetes') do |n|
@namespace = n
end
opts.on('-a', '--namespace NAMESPACE', 'Namespace do Kubernetes') do |n|
@namespace = n
end
opts.on('-c', '--configmap NAME', 'Nome do ConfigMap') do |c|
@configmap_name = c
end
opts.on('-s', '--secret NAME', 'Nome do Secret') do |s|
@secret_name = s
end
opts.on('-h', '--help', 'Mostra esta ajuda') do
show_help(opts)
exit
end
end.parse!
end
def show_help(opts)
puts opts
puts
puts 'Comandos:'
puts ' set KEY1=VALUE1 [KEY2=VALUE2 ...] Define variáveis de configuração'
puts ' set:secret KEY1=VALUE1 [KEY2=VALUE2 ...] Define variáveis secretas'
puts ' get [KEY] Lista variáveis ou uma específica'
puts ' unset KEY Remove uma variável'
puts ' unset:secret KEY Remove uma variável secreta'
puts ' restart Reinicia os pods'
puts
puts 'Exemplos:'
puts " #{$0} set -n production RAILS_ENV=production LOG_LEVEL=info"
puts " #{$0} set:secret -n staging DATABASE_URL=postgres://user:pass@host:5432/db"
puts " #{$0} get -n production"
puts " #{$0} get -n staging RAILS_ENV"
puts " #{$0} unset -n production DEBUG_MODE"
puts " #{$0} restart -n production"
end
def execute_command
command = ARGV.shift
case command
when 'set'
set_config(false)
when 'set:secret'
set_config(true)
when 'get'
get_config
when 'unset'
unset_config(false)
when 'unset:secret'
unset_config(true)
when 'restart'
restart_pods
else
puts "❌ Comando desconhecido: #{command}"
puts 'Use --help para ver os comandos disponíveis'
exit 1
end
end
def set_config(is_secret)
if ARGV.empty?
puts '❌ Especifique pelo menos uma variável KEY=VALUE'
exit 1
end
config_type = is_secret ? 'secret' : 'config'
puts "🔧 Definindo variáveis #{config_type} no namespace '#{@namespace}'..."
puts "📋 ConfigMap: #{@configmap_name}"
puts "🔐 Secret: #{@secret_name}"
puts
config_vars = {}
secret_vars = {}
ARGV.each do |arg|
unless arg.include?('=')
puts "❌ Formato inválido: '#{arg}'. Use: KEY=VALUE"
exit 1
end
key, value = arg.split('=', 2)
unless key =~ /^[A-Z_][A-Z0-9_]*$/
puts "❌ KEY inválida: '#{key}'. Use apenas letras maiúsculas, números e underscore"
exit 1
end
if is_secret
secret_vars[key] = Base64.strict_encode64(value)
else
config_vars[key] = value
end
end
# Aplicar mudanças no ConfigMap
if config_vars.any?
puts '🔧 Aplicando mudanças no ConfigMap...'
patch_configmap(config_vars)
puts '✅ ConfigMap atualizado com sucesso'
end
# Aplicar mudanças no Secret
if secret_vars.any?
puts '🔧 Aplicando mudanças no Secret...'
patch_secret(secret_vars)
puts '✅ Secret atualizado com sucesso'
end
# Mostrar resumo
puts
puts '🎉 Configurações aplicadas com sucesso!'
puts '📊 Resumo:'
puts " - Namespace: #{@namespace}"
puts " - ConfigMap: #{config_vars.size} variáveis"
puts " - Secret: #{secret_vars.size} variáveis"
if config_vars.any?
puts '📝 Variáveis do ConfigMap:'
config_vars.each { |k, v| puts " ✓ #{k} = #{v}" }
end
if secret_vars.any?
puts '🔐 Variáveis do Secret:'
secret_vars.each { |k, _| puts " ✓ #{k} = ***" }
end
end
def get_config
key = ARGV.first
puts "📋 Namespace: #{@namespace}"
puts "📋 ConfigMap: #{@configmap_name}"
puts "🔐 Secret: #{@secret_name}"
puts
if key
puts "🔍 Procurando por: #{key}"
# Procurar no ConfigMap
config_value = get_configmap_value(key)
if config_value
puts "✅ ConfigMap: #{key} = #{config_value}"
return
end
# Procurar no Secret
secret_value = get_secret_value(key)
if secret_value
puts "✅ Secret: #{key} = #{secret_value}"
return
end
puts "❌ Variável '#{key}' não encontrada"
exit 1
else
puts '📋 ConfigMap variables:'
configmap_data = get_configmap_data
puts JSON.pretty_generate(configmap_data)
puts '🔐 Secret variables:'
secret_data = get_secret_data
puts JSON.pretty_generate(secret_data)
end
end
def unset_config(is_secret)
key = ARGV.first
if key.nil?
puts '❌ Especifique KEY'
exit 1
end
config_type = is_secret ? 'secret' : 'config'
puts "�� Removendo #{config_type} no namespace '#{@namespace}'..."
if is_secret
puts "🔐 Removendo secret: #{key}"
patch_secret({ key => nil })
else
puts "📝 Removendo config: #{key}"
patch_configmap({ key => nil })
end
puts "✅ Configuração '#{key}' removida com sucesso"
end
def restart_pods
puts "🔄 Reiniciando pods no namespace '#{@namespace}'..."
result = system("kubectl rollout restart deployment/atendesimples-ws -n #{@namespace}")
if result
puts '✅ Pods reiniciados com sucesso'
puts "\u{1F9CA} Status do rollout:"
system("kubectl rollout status deployment/atendesimples-ws -n #{@namespace}")
else
puts '❌ Erro ao reiniciar pods'
exit 1
end
end
def patch_configmap(data)
patch = { data: data }.to_json
system("kubectl patch configmap #{@configmap_name} -n #{@namespace} -p '#{patch}' --type=merge")
end
def patch_secret(data)
patch = { data: data }.to_json
system("kubectl patch secret #{@secret_name} -n #{@namespace} -p '#{patch}' --type=merge")
end
def get_configmap_data
result = `kubectl get configmap #{@configmap_name} -n #{@namespace} -o jsonpath='{.data}' 2>/dev/null`
result.empty? ? {} : JSON.parse(result)
rescue JSON::ParserError
{}
end
def get_secret_data
result = `kubectl get secret #{@secret_name} -n #{@namespace} -o jsonpath='{.data}' 2>/dev/null`
return {} if result.empty?
JSON.parse(result)
rescue JSON::ParserError => e
puts "❌ Erro ao decodificar secret: #{e.message}"
{}
end
def get_configmap_value(key)
result = `kubectl get configmap #{@configmap_name} -n #{@namespace} -o jsonpath='{.data.#{key}}' 2>/dev/null`
result.empty? ? nil : result
end
def get_secret_value(key)
result = `kubectl get secret #{@secret_name} -n #{@namespace} -o jsonpath='{.data.#{key}}' 2>/dev/null`
return if result.empty?
Base64.strict_decode64(result)
rescue ArgumentError => e
puts "❌ Erro ao decodificar secret: #{e.message}"
nil
end
end
# Verificar se kubectl está disponível
unless system('which kubectl > /dev/null 2>&1')
puts '❌ kubectl não encontrado. Instale o kubectl primeiro.'
exit 1
end
# Executar o script
KubernetesConfig.run!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment