Class: Kubes::Kubectl::Batch

Inherits:
Object
  • Object
show all
Includes:
Hooks::Concern, Ordering, Logging, Util::Consider, Util::Sh
Defined in:
lib/kubes/kubectl/batch.rb

Instance Method Summary collapse

Methods included from Ordering

#config_skip?, #files, #filter_skip, #index_for, #process?, #search_expr, #sorted_files, #two_levels_deep?

Methods included from Util::Sh

#sh, #sh_capture

Methods included from Logging

#logger

Methods included from Util::Consider

#consider?

Methods included from Hooks::Concern

#run_hooks

Constructor Details

#initialize(name, options = {}) ⇒ Batch

Returns a new instance of Batch.



9
10
11
# File 'lib/kubes/kubectl/batch.rb', line 9

def initialize(name, options={})
  @name, @options = name.to_s, options
end

Instance Method Details

#pruneObject



30
31
32
33
34
# File 'lib/kubes/kubectl/batch.rb', line 30

def prune
  return unless @name == "apply" # only run for apply
  return unless Kubes.config.auto_prune # prune old secrets and config maps
  Kubes::CLI::Prune.new(@options.merge(yes: true, quiet: true)).run
end

#runObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/kubes/kubectl/batch.rb', line 13

def run
  # @options[:preview] is really only used for kubectl delete
  logger.info "Will run:" if @options[:preview]
  switch_context do
    run_hooks("kubes.rb", name: @name) do
      sorted_files.each do |file|
        if @options[:preview]
          logger.info "    kubectl #{@name} -f #{file}"
        else
          Kubes::Kubectl.run(@name, @options.merge(file: file))
        end
      end
      prune # important to call within run_hooks for case of GKE IP whitelisting
    end
  end
end

#switch_context(&block) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/kubes/kubectl/batch.rb', line 36

def switch_context(&block)
  kubectl = Kubes.config.kubectl
  context = kubectl.context

  unless context
    block.call
    return
  end

  previous_context = sh_capture("kubectl config current-context")
  if previous_context == context
    block.call
    return
  end

  logger.debug "Switching kubectl context to: #{context}"
  sh("kubectl config use-context #{context}", mute: true)
  result = block.call
  if !previous_context.blank? && !kubectl.context_keep
    sh("kubectl config use-context #{previous_context}", mute: true)
  end
  result
end