summaryrefslogtreecommitdiff
path: root/app/services/ci/generate_kubeconfig_service.rb
blob: 1c6aaa9d1ff2b5013e94ad5e8d4cdc3bd51c2a54 (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# frozen_string_literal: true

module Ci
  class GenerateKubeconfigService
    def initialize(pipeline, token:, environment:)
      @pipeline = pipeline
      @token = token
      @environment = environment

      @template = Gitlab::Kubernetes::Kubeconfig::Template.new
    end

    def execute
      template.add_cluster(
        name: cluster_name,
        url: Gitlab::Kas.tunnel_url
      )

      agent_authorizations.each do |authorization|
        agent = authorization.agent
        user = user_name(agent)

        template.add_user(
          name: user,
          token: agent_token(agent)
        )

        template.add_context(
          name: context_name(agent),
          namespace: context_namespace(authorization),
          cluster: cluster_name,
          user: user
        )
      end

      template
    end

    private

    attr_reader :pipeline, :token, :environment, :template

    def agent_authorizations
      ::Clusters::Agents::FilterAuthorizationsService.new(
        pipeline.cluster_agent_authorizations,
        environment: environment
      ).execute
    end

    def cluster_name
      'gitlab'
    end

    def user_name(agent)
      ['agent', agent.id].join(delimiter)
    end

    def context_name(agent)
      [agent.project.full_path, agent.name].join(delimiter)
    end

    def context_namespace(authorization)
      authorization.config['default_namespace']
    end

    def agent_token(agent)
      ['ci', agent.id, token].join(delimiter)
    end

    def delimiter
      ':'
    end
  end
end