# helm_charts_jenkins-master-networkpolicy.yaml
{{- if .Values.networkPolicy.enabled }}
kind: NetworkPolicy
apiVersion: {{ .Values.networkPolicy.apiVersion }}
metadata:
  name: "{{ .Release.Name }}-{{ .Values.master.componentName }}"
  namespace: {{ template "jenkins.namespace" . }}
  labels:
    "app.kubernetes.io/name": '{{ template "jenkins.name" .}}'
    "helm.sh/chart": "{{ .Chart.Name }}-{{ .Chart.Version }}"
    "app.kubernetes.io/managed-by": "{{ .Release.Service }}"
    "app.kubernetes.io/instance": "{{ .Release.Name }}"
    "app.kubernetes.io/component": "{{ .Values.master.componentName }}"
spec:
  podSelector:
    matchLabels:
      "app.kubernetes.io/component": "{{ .Values.master.componentName }}"
      "app.kubernetes.io/instance": "{{ .Release.Name }}"
  ingress:
    # Allow web access to the UI
    - ports:
      - port: {{ .Values.master.targetPort }}
    # Allow inbound connections from slave
    - from:
      {{- if .Values.networkPolicy.internalAgents.allowed }}
      - podSelector:
          matchLabels:
            "jenkins/{{ .Release.Name }}-{{ .Values.agent.componentName }}": "true"
            {{- range $k,$v:= .Values.networkPolicy.internalAgents.podLabels }}
            {{ $k }}: {{ $v }}
            {{- end }}
        {{- if .Values.networkPolicy.internalAgents.namespaceLabels }}
        namespaceSelector:
          matchLabels:
            {{- range $k,$v:= .Values.networkPolicy.internalAgents.namespaceLabels }}
            {{ $k }}: {{ $v }}
            {{- end }}
        {{- end }}    
      {{- end }}
      {{- if .Values.networkPolicy.externalAgents }}      
      - ipBlock:
          cidr: {{ required "ipCIDR is required if you wish to allow external agents to connect to Master." .Values.networkPolicy.externalAgents.ipCIDR }}
          {{- if .Values.networkPolicy.externalAgents.except }}
          except:
          {{- range .Values.networkPolicy.externalAgents.except }}
          - {{ . }} 
          {{- end }}
          {{- end }}
      {{- end }}              
      ports:
      - port: {{ .Values.master.slaveListenerPort }}
{{- if .Values.agent.enabled }}
---
kind: NetworkPolicy
apiVersion: {{ .Values.networkPolicy.apiVersion }}
metadata:
  name: "{{ .Release.Name }}-{{ .Values.agent.componentName }}"
  namespace: {{ template "jenkins.namespace" . }}
  labels:
    "app.kubernetes.io/name": '{{ template "jenkins.name" .}}'
    "helm.sh/chart": "{{ .Chart.Name }}-{{ .Chart.Version }}"
    "app.kubernetes.io/managed-by": "{{ .Release.Service }}"
    "app.kubernetes.io/instance": "{{ .Release.Name }}"
    "app.kubernetes.io/component": "{{ .Values.master.componentName }}"
spec:
  podSelector:
    matchLabels:
      # DefaultDeny
      "jenkins/{{ .Release.Name }}-{{ .Values.agent.componentName }}": "true"
{{- end }}
{{- end }}