Class: Kube::Cluster::Middleware::ServiceForDeployment

Inherits:
Kube::Cluster::Middleware show all
Defined in:
lib/kube/cluster/middleware/service_for_deployment.rb

Overview

Generates a Service for every pod-bearing resource that has containers with named ports.

The generated Service uses spec.selector.matchLabels from the source resource and maps each named container port.

Labels and namespace are copied from the source resource, so subsequent middleware (Labels, Namespace, etc.) will also apply to the generated Service.

stack do
  use Middleware::ServiceForDeployment
end

Instance Method Summary collapse

Methods inherited from Kube::Cluster::Middleware

#initialize

Constructor Details

This class inherits a constructor from Kube::Cluster::Middleware

Instance Method Details

#call(manifest) ⇒ Object



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
# File 'lib/kube/cluster/middleware/service_for_deployment.rb', line 21

def call(manifest)
  generated = []

  manifest.resources.each do |resource|
    next unless resource.pod_bearing?

    h = resource.to_h
    ports = extract_ports(resource, h)
    next if ports.empty?

    match_labels = h.dig(:spec, :selector, :matchLabels)
    next unless match_labels && !match_labels.empty?

    generated << Kube::Cluster["Service"].new {
      .name      = h.dig(:metadata, :name)
      .namespace = h.dig(:metadata, :namespace) if h.dig(:metadata, :namespace)
      .labels    = h.dig(:metadata, :labels) || {}

      spec.selector = match_labels
      spec.ports = ports.map { |p|
        {
          name:       p[:name],
          port:       p[:containerPort],
          targetPort: p[:name],
          protocol:   p.fetch(:protocol, "TCP"),
        }
      }
    }
  end

  manifest.resources.concat(generated)
end