summaryrefslogtreecommitdiff
path: root/lib/gitlab/kubernetes/kubeconfig/template.rb
blob: da0861ee86ac36ac471cbaf72a05a555a2fba429 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# frozen_string_literal: true

module Gitlab
  module Kubernetes
    module Kubeconfig
      class Template
        ENTRIES = {
          cluster: Gitlab::Kubernetes::Kubeconfig::Entry::Cluster,
          user: Gitlab::Kubernetes::Kubeconfig::Entry::User,
          context: Gitlab::Kubernetes::Kubeconfig::Entry::Context
        }.freeze

        def initialize
          @clusters = []
          @users = []
          @contexts = []
        end

        def valid?
          contexts.present?
        end

        def add_cluster(**args)
          clusters << new_entry(:cluster, **args)
        end

        def add_user(**args)
          users << new_entry(:user, **args)
        end

        def add_context(**args)
          contexts << new_entry(:context, **args)
        end

        def to_h
          {
            apiVersion: 'v1',
            kind: 'Config',
            clusters: clusters.map(&:to_h),
            users: users.map(&:to_h),
            contexts: contexts.map(&:to_h)
          }
        end

        def to_yaml
          YAML.dump(to_h.deep_stringify_keys)
        end

        private

        attr_reader :clusters, :users, :contexts

        def new_entry(entry, **args)
          ENTRIES.fetch(entry).new(**args)
        end
      end
    end
  end
end