# _helpers.tpl
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "jenkins.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
Allow the release namespace to be overridden for multi-namespace deployments in combined charts.
*/}}
{{- define "jenkins.namespace" -}}
  {{- if .Values.namespaceOverride -}}
    {{- .Values.namespaceOverride -}}
  {{- else -}}
    {{- .Release.Namespace -}}
  {{- end -}}
{{- end -}}

{{- define "jenkins.master.slaveKubernetesNamespace" -}}
  {{- if .Values.master.slaveKubernetesNamespace -}}
    {{- tpl .Values.master.slaveKubernetesNamespace . -}}
  {{- else -}}
    {{- if .Values.namespaceOverride -}}
      {{- .Values.namespaceOverride -}}
    {{- else -}}
      {{- .Release.Namespace -}}
    {{- end -}}
  {{- end -}}
{{- end -}}


{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "jenkins.fullname" -}}
{{- if .Values.fullnameOverride -}}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- $name := default .Chart.Name .Values.nameOverride -}}
{{- if contains $name .Release.Name -}}
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- end -}}

{{/*
Returns the Jenkins URL
*/}}
{{- define "jenkins.url" -}}
{{- if .Values.master.jenkinsUrl }}
  {{- .Values.master.jenkinsUrl }}
{{- else }}
  {{- if .Values.master.ingress.hostName }}
    {{- if .Values.master.ingress.tls }}
      {{- default "https" .Values.master.jenkinsUrlProtocol }}://{{ .Values.master.ingress.hostName }}{{ default "" .Values.master.jenkinsUriPrefix }}
    {{- else }}
      {{- default "http" .Values.master.jenkinsUrlProtocol }}://{{ .Values.master.ingress.hostName }}{{ default "" .Values.master.jenkinsUriPrefix }}
    {{- end }}
  {{- else }}
      {{- default "http" .Values.master.jenkinsUrlProtocol }}://{{ template "jenkins.fullname" . }}:{{.Values.master.servicePort}}{{ default "" .Values.master.jenkinsUriPrefix }}
  {{- end}}
{{- end}}
{{- end -}}

{{/*
Returns configuration as code default config
*/}}
{{- define "jenkins.casc.defaults" -}}
jenkins:
{{- if eq .Values.master.enableXmlConfig false }}
  {{- $configScripts := toYaml .Values.master.JCasC.configScripts }}
  {{- if and (.Values.master.JCasC.authorizationStrategy) (not (contains "authorizationStrategy:" $configScripts)) }}
  authorizationStrategy:
    {{- tpl .Values.master.JCasC.authorizationStrategy . | nindent 4 }}
  {{- end }}
  {{- if and (.Values.master.JCasC.securityRealm) (not (contains "securityRealm:" $configScripts)) }}
  securityRealm:
    {{- tpl .Values.master.JCasC.securityRealm . | nindent 4 }}
  {{- end }}
{{- end }}
  disableRememberMe: {{ .Values.master.disableRememberMe }}
  remotingSecurity:
    enabled: true
  mode: {{ .Values.master.executorMode }}
  numExecutors: {{ .Values.master.numExecutors }}
  projectNamingStrategy: "standard"
  markupFormatter:
    {{- if .Values.master.enableRawHtmlMarkupFormatter }}
    rawHtml:
      disableSyntaxHighlighting: true
    {{- else }}
    {{- toYaml .Values.master.markupFormatter | nindent 4 }}
    {{- end }}
  clouds:
  - kubernetes:
      containerCapStr: "{{ .Values.agent.containerCap }}"
      defaultsProviderTemplate: "{{ .Values.master.slaveDefaultsProviderTemplate }}"
      connectTimeout: "{{ .Values.master.slaveConnectTimeout }}"
      readTimeout: "{{ .Values.master.slaveReadTimeout }}"
      {{- if .Values.master.slaveJenkinsUrl }}
      jenkinsUrl: "{{ tpl .Values.master.slaveJenkinsUrl . }}"
      {{- else if .Values.master.slaveKubernetesNamespace }}
      jenkinsUrl: "http://{{ template "jenkins.fullname" . }}.{{ template "jenkins.namespace" . }}:{{.Values.master.servicePort}}{{ default "" .Values.master.jenkinsUriPrefix }}"
      {{- else }}
      jenkinsUrl: "http://{{ template "jenkins.fullname" . }}:{{.Values.master.servicePort}}{{ default "" .Values.master.jenkinsUriPrefix }}"
      {{- end }}

      {{- if .Values.master.slaveJenkinsTunnel }}
      jenkinsTunnel: "{{ tpl .Values.master.slaveJenkinsTunnel . }}"
      {{- else if .Values.master.slaveKubernetesNamespace }}
      jenkinsTunnel: "{{ template "jenkins.fullname" . }}-agent.{{ template "jenkins.namespace" . }}:{{ .Values.master.slaveListenerPort }}"
      {{- else }}
      jenkinsTunnel: "{{ template "jenkins.fullname" . }}-agent:{{ .Values.master.slaveListenerPort }}"
      {{- end }}
      maxRequestsPerHostStr: "32"
      name: "kubernetes"
      namespace: "{{ template "jenkins.master.slaveKubernetesNamespace" . }}"
      serverUrl: "https://kubernetes.default"
      {{- if .Values.agent.enabled }}
      podLabels:
      - key: "jenkins/{{ .Release.Name }}-{{ .Values.agent.componentName }}"
        value: "true"
      templates:
      {{- include "jenkins.casc.podTemplate" . | nindent 8 }}
    {{- if .Values.additionalAgents }}
      {{- /* save .Values.agent */}}
      {{- $agent := .Values.agent }}
      {{- range $name, $additionalAgent := .Values.additionalAgents }}
        {{- /* merge original .Values.agent into additional agent to ensure it at least has the default values */}}
        {{- $additionalAgent := merge $additionalAgent $agent }}
        {{- /* set .Values.agent to $additionalAgent */}}
        {{- $_ := set $.Values "agent" $additionalAgent }}
        {{- include "jenkins.casc.podTemplate" $ | nindent 8 }}
      {{- end }}
      {{- /* restore .Values.agent */}}
      {{- $_ := set .Values "agent" $agent }}
    {{- end }}
      {{- if .Values.agent.podTemplates }}
        {{- range $key, $val := .Values.agent.podTemplates }}
          {{- tpl $val $ | nindent 8 }}
        {{- end }}
      {{- end }}
      {{- end }}
  {{- if .Values.master.csrf.defaultCrumbIssuer.enabled }}
  crumbIssuer:
    standard:
      excludeClientIPFromCrumb: {{ if .Values.master.csrf.defaultCrumbIssuer.proxyCompatability }}true{{ else }}false{{- end }}
  {{- end }}
security:
  apiToken:
    creationOfLegacyTokenEnabled: false
    tokenGenerationOnCreationEnabled: false
    usageStatisticsEnabled: true
unclassified:
  location:
    adminAddress: {{ default "" .Values.master.jenkinsAdminEmail }}
    url: {{ template "jenkins.url" . }}
{{- end -}}

{{/*
Returns kubernetes pod template configuration as code
*/}}
{{- define "jenkins.casc.podTemplate" -}}
- name: "{{ .Values.agent.podName }}"
  containers:
  - name: "{{ .Values.agent.sideContainerName }}"
    alwaysPullImage: {{ .Values.agent.alwaysPullImage }}
    args: "{{ .Values.agent.args | replace "$" "^$" }}"
    {{- if .Values.agent.command }}
    command: {{ .Values.agent.command }}
    {{- end }}
    envVars:
      - envVar:
          key: "JENKINS_URL"
          {{- if .Values.master.slaveJenkinsUrl }}
          value: {{ tpl .Values.master.slaveJenkinsUrl . }}
          {{- else }}
          value: "http://{{ template "jenkins.fullname" . }}.{{ template "jenkins.namespace" . }}.svc.{{.Values.clusterZone}}:{{.Values.master.servicePort}}{{ default "" .Values.master.jenkinsUriPrefix }}"
          {{- end }}
    {{- if .Values.agent.imageTag }}
    image: "{{ .Values.agent.image }}:{{ .Values.agent.imageTag }}"
    {{- else }}
    image: "{{ .Values.agent.image }}:{{ .Values.agent.tag }}"
    {{- end }}
    privileged: "{{- if .Values.agent.privileged }}true{{- else }}false{{- end }}"
    resourceLimitCpu: {{.Values.agent.resources.limits.cpu}}
    resourceLimitMemory: {{.Values.agent.resources.limits.memory}}
    resourceRequestCpu: {{.Values.agent.resources.requests.cpu}}
    resourceRequestMemory: {{.Values.agent.resources.requests.memory}}
    runAsUser: {{ .Values.agent.runAsUser }}
    runAsGroup: {{ .Values.agent.runAsGroup }}
    ttyEnabled: {{ .Values.agent.TTYEnabled }}
    workingDir: {{ .Values.agent.workingDir }}
{{- if .Values.agent.envVars }}
  envVars:
  {{- range $index, $var := .Values.agent.envVars }}
    - envVar:
        key: {{ $var.name }}
        value: {{ tpl $var.value $ }}
  {{- end }}
{{- end }}
  idleMinutes: {{ .Values.agent.idleMinutes }}
  instanceCap: 2147483647
  {{- if .Values.agent.imagePullSecretName }}
  imagePullSecrets:
  - name: {{ .Values.agent.imagePullSecretName }}
  {{- end }}
  label: "{{ .Release.Name }}-{{ .Values.agent.componentName }} {{ .Values.agent.customJenkinsLabels  | join " " }}"
{{- if .Values.agent.nodeSelector }}
  nodeSelector:
  {{- $local := dict "first" true }}
  {{- range $key, $value := .Values.agent.nodeSelector }}
    {{- if $local.first }} {{ else }},{{ end }}
    {{- $key }}={{ tpl $value $ }}
    {{- $_ := set $local "first" false }}
  {{- end }}
{{- end }}
  nodeUsageMode: "NORMAL"
  podRetention: {{ .Values.agent.podRetention }}
  showRawYaml: true
  serviceAccount: "{{ include "jenkins.serviceAccountAgentName" . }}"
  slaveConnectTimeoutStr: "{{ .Values.agent.slaveConnectTimeout }}"
{{- if .Values.agent.volumes }}
  volumes:
  {{- range $index, $volume := .Values.agent.volumes }}
    -{{- if (eq $volume.type "ConfigMap") }} configMapVolume:
     {{- else if (eq $volume.type "EmptyDir") }} emptyDirVolume:
     {{- else if (eq $volume.type "HostPath") }} hostPathVolume:
     {{- else if (eq $volume.type "Nfs") }} nfsVolume:
     {{- else if (eq $volume.type "PVC") }} persistentVolumeClaim:
     {{- else if (eq $volume.type "Secret") }} secretVolume:
     {{- else }} {{ $volume.type }}:
     {{- end }}
    {{- range $key, $value := $volume }}
      {{- if not (eq $key "type") }}
        {{ $key }}: {{ if kindIs "string" $value }}{{ tpl $value $ | quote }}{{ else }}{{ $value }}{{ end }}
      {{- end }}
    {{- end }}
  {{- end }}
{{- end }}
{{- if .Values.agent.yamlTemplate }}
  yaml: |-
    {{- tpl (trim .Values.agent.yamlTemplate) . | nindent 4 }}
{{- end }}
  yamlMergeStrategy: {{ .Values.agent.yamlMergeStrategy }}
{{- end -}}

{{/*
Returns kubernetes pod template xml configuration
*/}}
{{- define "jenkins.xml.podTemplate" -}}
<org.csanchez.jenkins.plugins.kubernetes.PodTemplate>
  <inheritFrom></inheritFrom>
  <name>{{ .Values.agent.podName }}</name>
  <instanceCap>2147483647</instanceCap>
  <idleMinutes>{{ .Values.agent.idleMinutes }}</idleMinutes>
  {{- $tmp := join " " .Values.agent.customJenkinsLabels }}
  {{- $labels := printf "%s-%s %s" .Release.Name .Values.agent.componentName $tmp }}
  <label>{{ $labels | trim  }}</label>
  <serviceAccount>{{ include "jenkins.serviceAccountAgentName" . }}</serviceAccount>
  <nodeSelector>
    {{- $local := dict "first" true }}
    {{- range $key, $value := .Values.agent.nodeSelector }}
      {{- if not $local.first }},{{- end }}
      {{- $key }}={{ $value }}
      {{- $_ := set $local "first" false }}
    {{- end }}</nodeSelector>
    <nodeUsageMode>NORMAL</nodeUsageMode>
  <volumes>
{{- range $index, $volume := .Values.agent.volumes }}
  {{- if (eq $volume.type "PVC") }}
    <org.csanchez.jenkins.plugins.kubernetes.volumes.PersistentVolumeClaim>
  {{- else }}
    <org.csanchez.jenkins.plugins.kubernetes.volumes.{{ $volume.type }}Volume>
  {{- end }}
  {{- range $key, $value := $volume }}{{- if not (eq $key "type") }}
      <{{ $key }}>{{ if kindIs "string" $value }}{{ tpl $value $ }}{{ else }}{{ $value }}{{ end }}</{{ $key }}>
  {{- end }}{{- end }}
  {{- if (eq $volume.type "PVC") }}
    </org.csanchez.jenkins.plugins.kubernetes.volumes.PersistentVolumeClaim>
  {{- else }}
    </org.csanchez.jenkins.plugins.kubernetes.volumes.{{ $volume.type }}Volume>
  {{- end }}
{{- end }}
  </volumes>
  <containers>
    <org.csanchez.jenkins.plugins.kubernetes.ContainerTemplate>
      <name>{{ .Values.agent.sideContainerName }}</name>
{{- if .Values.agent.imageTag }}
      <image>{{ .Values.agent.image }}:{{ .Values.agent.imageTag }}</image>
{{- else }}
      <image>{{ .Values.agent.image }}:{{ .Values.agent.tag }}</image>
{{- end }}
{{- if .Values.agent.privileged }}
      <privileged>true</privileged>
{{- else }}
      <privileged>false</privileged>
{{- end }}
      <alwaysPullImage>{{ .Values.agent.alwaysPullImage }}</alwaysPullImage>
      <workingDir>{{ .Values.agent.workingDir }}</workingDir>
      <command>{{ .Values.agent.command }}</command>
      <args>{{ .Values.agent.args }}</args>
      <ttyEnabled>{{ .Values.agent.TTYEnabled }}</ttyEnabled>
      # Resources configuration is a little hacky. This was to prevent breaking
      # changes, and should be cleanned up in the future once everybody had
      # enough time to migrate.
      <resourceRequestCpu>{{.Values.agent.resources.requests.cpu}}</resourceRequestCpu>
      <resourceRequestMemory>{{.Values.agent.resources.requests.memory}}</resourceRequestMemory>
      <resourceLimitCpu>{{.Values.agent.resources.limits.cpu}}</resourceLimitCpu>
      <resourceLimitMemory>{{.Values.agent.resources.limits.memory}}</resourceLimitMemory>
      <envVars>
        <org.csanchez.jenkins.plugins.kubernetes.ContainerEnvVar>
          <key>JENKINS_URL</key>
{{- if .Values.master.slaveJenkinsUrl }}
          <value>{{ tpl .Values.master.slaveJenkinsUrl . }}</value>
{{- else }}
          <value>http://{{ template "jenkins.fullname" . }}.{{ template "jenkins.namespace" . }}.svc.{{.Values.clusterZone}}:{{.Values.master.servicePort}}{{ default "" .Values.master.jenkinsUriPrefix }}</value>
{{- end }}
        </org.csanchez.jenkins.plugins.kubernetes.ContainerEnvVar>
      </envVars>
    </org.csanchez.jenkins.plugins.kubernetes.ContainerTemplate>
  </containers>
  <envVars>
{{- range $index, $var := .Values.agent.envVars }}
    <org.csanchez.jenkins.plugins.kubernetes.PodEnvVar>
      <key>{{ $var.name }}</key>
      <value>{{ $var.value }}</value>
    </org.csanchez.jenkins.plugins.kubernetes.PodEnvVar>
{{- end }}
  </envVars>
  <annotations/>
{{- if .Values.agent.imagePullSecretName }}
  <imagePullSecrets>
    <org.csanchez.jenkins.plugins.kubernetes.PodImagePullSecret>
      <name>{{ .Values.agent.imagePullSecretName }}</name>
    </org.csanchez.jenkins.plugins.kubernetes.PodImagePullSecret>
  </imagePullSecrets>
{{- else }}
  <imagePullSecrets/>
{{- end }}
  <nodeProperties/>
{{- if .Values.agent.yamlTemplate }}
  <yaml>
    {{- tpl (trim .Values.agent.yamlTemplate) . | html | nindent 4 }}
  </yaml>
{{- end }}
  <podRetention class="org.csanchez.jenkins.plugins.kubernetes.pod.retention.Default"/>
</org.csanchez.jenkins.plugins.kubernetes.PodTemplate>
{{- end -}}

{{- define "jenkins.kubernetes-version" -}}
  {{- if .Values.master.installPlugins -}}
    {{- range .Values.master.installPlugins -}}
      {{ if hasPrefix "kubernetes:" . }}
        {{- $split := splitList ":" . }}
        {{- printf "%s" (index $split 1 ) -}}
      {{- end -}}
    {{- end -}}
  {{- end -}}
{{- end -}}

{{/*
Create the name of the service account to use
*/}}
{{- define "jenkins.serviceAccountName" -}}
{{- if .Values.serviceAccount.create -}}
    {{ default (include "jenkins.fullname" .) .Values.serviceAccount.name }}
{{- else -}}
    {{ default "default" .Values.serviceAccount.name }}
{{- end -}}
{{- end -}}

{{/*
Create the name of the service account for Jenkins agents to use
*/}}
{{- define "jenkins.serviceAccountAgentName" -}}
{{- if .Values.serviceAccountAgent.create -}}
    {{ default (printf "%s-%s" (include "jenkins.fullname" .) "agent") .Values.serviceAccountAgent.name }}
{{- else -}}
    {{ default "default" .Values.serviceAccountAgent.name }}
{{- end -}}
{{- end -}}
 # config.yaml
{{- if not .Values.master.customConfigMap }}
{{- $jenkinsHome := .Values.master.jenkinsHome -}}

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "jenkins.fullname" . }}
  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 }}"
data:
{{- if .Values.master.enableXmlConfig }}
  config.xml: |-
    <?xml version='1.0' encoding='UTF-8'?>
    <hudson>
      <disabledAdministrativeMonitors/>
{{- if .Values.master.imageTag }}
      <version>{{ .Values.master.imageTag }}</version>
{{- else }}
      <version>{{ .Values.master.tag }}</version>
{{- end }}
      <numExecutors>{{ .Values.master.numExecutors }}</numExecutors>
      <mode>{{ .Values.master.executorMode }}</mode>
      <useSecurity>{{ .Values.master.useSecurity }}</useSecurity>
{{ .Values.master.authorizationStrategy | indent 6 }}
{{ .Values.master.securityRealm | indent 6 }}
      <disableRememberMe>{{ .Values.master.disableRememberMe }}</disableRememberMe>
      <projectNamingStrategy class="jenkins.model.ProjectNamingStrategy$DefaultProjectNamingStrategy"/>
      <workspaceDir>${JENKINS_HOME}/workspace/${ITEM_FULLNAME}</workspaceDir>
      <buildsDir>${ITEM_ROOTDIR}/builds</buildsDir>
{{- if .Values.master.enableRawHtmlMarkupFormatter }}
      <markupFormatter class="hudson.markup.RawHtmlMarkupFormatter" plugin="antisamy-markup-formatter">
        <disableSyntaxHighlighting>true</disableSyntaxHighlighting>
      </markupFormatter>
{{- else }}
      <markupFormatter class="hudson.markup.EscapedMarkupFormatter"/>
{{- end }}
      <jdks/>
      <viewsTabBar class="hudson.views.DefaultViewsTabBar"/>
      <myViewsTabBar class="hudson.views.DefaultMyViewsTabBar"/>
      <clouds>
        <org.csanchez.jenkins.plugins.kubernetes.KubernetesCloud plugin="kubernetes@{{ template "jenkins.kubernetes-version" . }}">
          <name>kubernetes</name>
          <defaultsProviderTemplate>{{ .Values.master.slaveDefaultsProviderTemplate }}</defaultsProviderTemplate>
          <templates>
{{- if .Values.agent.enabled }}
  {{- include "jenkins.xml.podTemplate" . | nindent 12 }}
  {{- if .Values.additionalAgents }}
    {{- /* save .Values.agent */}}
    {{- $agent := .Values.agent }}
    {{- range $name, $additionalAgent := .Values.additionalAgents }}
      {{- /* merge original .Values.agent into additional agent to ensure it at least has the default values */}}
      {{- $additionalAgent := merge $additionalAgent $agent }}
      {{- /* set .Values.agent to $additionalAgent */}}
      {{- $_ := set $.Values "agent" $additionalAgent }}
      {{- include "jenkins.xml.podTemplate" $ | nindent 12 }}
    {{- end }}
    {{- /* restore .Values.agent */}}
    {{- $_ := set .Values "agent" $agent }}
  {{- end }}
{{- end }}
          </templates>
          <serverUrl>https://kubernetes.default</serverUrl>
          <skipTlsVerify>false</skipTlsVerify>
          <namespace>{{ template "jenkins.master.slaveKubernetesNamespace" . }}</namespace>
{{- if .Values.master.slaveJenkinsUrl }}
          <jenkinsUrl>{{ tpl .Values.master.slaveJenkinsUrl . }}</jenkinsUrl>
{{- else if .Values.master.slaveKubernetesNamespace }}
          <jenkinsUrl>http://{{ template "jenkins.fullname" . }}.{{ template "jenkins.namespace" . }}:{{.Values.master.servicePort}}{{ default "" .Values.master.jenkinsUriPrefix }}</jenkinsUrl>
{{- else }}
          <jenkinsUrl>http://{{ template "jenkins.fullname" . }}:{{.Values.master.servicePort}}{{ default "" .Values.master.jenkinsUriPrefix }}</jenkinsUrl>
{{- end }}

{{- if .Values.master.slaveJenkinsTunnel }}
          <jenkinsTunnel>{{ tpl .Values.master.slaveJenkinsTunnel . }}</jenkinsTunnel>
{{- else if .Values.master.slaveKubernetesNamespace }}
          <jenkinsTunnel>{{ template "jenkins.fullname" . }}-agent.{{ template "jenkins.namespace" . }}:{{ .Values.master.slaveListenerPort }}</jenkinsTunnel>
{{- else }}
          <jenkinsTunnel>{{ template "jenkins.fullname" . }}-agent:{{ .Values.master.slaveListenerPort }}</jenkinsTunnel>
{{- end }}
          <containerCap>{{ .Values.agent.containerCap }}</containerCap>
          <retentionTimeout>5</retentionTimeout>
          <connectTimeout>{{ .Values.master.slaveConnectTimeout }}</connectTimeout>
          <readTimeout>{{ .Values.master.slaveReadTimeout }}</readTimeout>
          <podLabels>
            <org.csanchez.jenkins.plugins.kubernetes.PodLabel>
              <key>jenkins/{{ .Release.Name }}-{{ .Values.agent.componentName }}</key>
              <value>true</value>
            </org.csanchez.jenkins.plugins.kubernetes.PodLabel>
          </podLabels>
          <podRetention class="org.csanchez.jenkins.plugins.kubernetes.pod.retention.{{ .Values.agent.podRetention }}"/>
        </org.csanchez.jenkins.plugins.kubernetes.KubernetesCloud>
      </clouds>
      <quietPeriod>5</quietPeriod>
      <scmCheckoutRetryCount>0</scmCheckoutRetryCount>
      <views>
        <hudson.model.AllView>
          <owner class="hudson" reference="../../.."/>
          <name>All</name>
          <filterExecutors>false</filterExecutors>
          <filterQueue>false</filterQueue>
          <properties class="hudson.model.View$PropertyList"/>
        </hudson.model.AllView>
      </views>
      <primaryView>All</primaryView>
      <slaveAgentPort>{{ .Values.master.slaveListenerPort }}</slaveAgentPort>
      <disabledAgentProtocols>
{{- range .Values.master.disabledAgentProtocols }}
        <string>{{ . }}</string>
{{- end }}
      </disabledAgentProtocols>
      <label>{{ .Values.master.customJenkinsLabels | join " " }}</label>
{{- if .Values.master.csrf.defaultCrumbIssuer.enabled }}
      <crumbIssuer class="hudson.security.csrf.DefaultCrumbIssuer">
{{- if .Values.master.csrf.defaultCrumbIssuer.proxyCompatability }}
        <excludeClientIPFromCrumb>true</excludeClientIPFromCrumb>
{{- end }}
      </crumbIssuer>
{{- end }}
      <nodeProperties/>
      <globalNodeProperties/>
      <noUsageStatistics>true</noUsageStatistics>
    </hudson>
{{- if .Values.master.scriptApproval }}
  scriptapproval.xml: |-
    <?xml version='1.0' encoding='UTF-8'?>
    <scriptApproval plugin="script-security@1.27">
      <approvedScriptHashes/>
      <approvedSignatures>
{{- range $key, $val := .Values.master.scriptApproval }}
        <string>{{ $val }}</string>
{{- end }}
      </approvedSignatures>
      <aclApprovedSignatures/>
      <approvedClasspathEntries/>
      <pendingScripts/>
      <pendingSignatures/>
      <pendingClasspathEntries/>
    </scriptApproval>
{{- end }}
  jenkins.model.JenkinsLocationConfiguration.xml: |-
    <?xml version='1.1' encoding='UTF-8'?>
    <jenkins.model.JenkinsLocationConfiguration>
      <adminAddress>{{ default "" .Values.master.jenkinsAdminEmail }}</adminAddress>
      <jenkinsUrl>{{ template "jenkins.url" . }}</jenkinsUrl>
    </jenkins.model.JenkinsLocationConfiguration>
  jenkins.CLI.xml: |-
    <?xml version='1.1' encoding='UTF-8'?>
    <jenkins.CLI>
{{- if .Values.master.cli }}
      <enabled>true</enabled>
{{- else }}
      <enabled>false</enabled>
{{- end }}
    </jenkins.CLI>
{{- end }}
  apply_config.sh: |-
{{- if .Values.master.initializeOnce }}
    if [ -f {{ .Values.master.jenkinsHome }}/initialization-completed ]; then
      echo "master was previously initialized, refusing to re-initialize"
      exit 0
    fi
{{- end }}
    echo "applying Jenkins configuration"
    mkdir -p {{ .Values.master.jenkinsRef }}/secrets/;
{{- if .Values.master.enableXmlConfig }}
    echo "apply XML configuration"
    echo "false" > {{ .Values.master.jenkinsRef }}/secrets/slave-to-master-security-kill-switch;
{{- if .Values.master.overwriteConfig }}
    echo "overwriting existing configuration"
    cp /var/jenkins_config/config.xml {{ .Values.master.jenkinsHome }};
    cp /var/jenkins_config/jenkins.CLI.xml {{ .Values.master.jenkinsHome }};
    cp /var/jenkins_config/jenkins.model.JenkinsLocationConfiguration.xml {{ .Values.master.jenkinsHome }};
  {{- if .Values.master.additionalConfig }}
  {{- range $key, $val := .Values.master.additionalConfig }}
    echo "copying additional configuration"
    cp /var/jenkins_config/{{- $key }} {{ $jenkinsHome }};
  {{- end }}
  {{- end }}
{{- else }}
    echo "copy XML configuration"
    yes n | cp -i /var/jenkins_config/config.xml {{ .Values.master.jenkinsHome }};
    yes n | cp -i /var/jenkins_config/jenkins.CLI.xml {{ .Values.master.jenkinsHome }};
    yes n | cp -i /var/jenkins_config/jenkins.model.JenkinsLocationConfiguration.xml {{ .Values.master.jenkinsHome }};
  {{- if .Values.master.additionalConfig }}
  {{- range $key, $val := .Values.master.additionalConfig }}
    yes n | cp -i /var/jenkins_config/{{- $key }} {{ $jenkinsHome }};
  {{- end }}
  {{- end }}
{{- end }}
{{- else }}
{{- if .Values.master.JCasC.enabled }}
    echo "disable Setup Wizard"
    # Prevent Setup Wizard when JCasC is enabled
    echo $JENKINS_VERSION > {{ .Values.master.jenkinsHome }}/jenkins.install.UpgradeWizard.state
    echo $JENKINS_VERSION > {{ .Values.master.jenkinsHome }}/jenkins.install.InstallUtil.lastExecVersion
{{- end }}
{{- end }}
{{- if .Values.master.overwritePlugins }}
    echo "remove all plugins from shared volume"
    # remove all plugins from shared volume
    rm -rf {{ .Values.master.jenkinsHome }}/plugins/*
{{- end }}
{{- if .Values.master.installPlugins }}
    echo "download plugins"
    # Install missing plugins
    cp /var/jenkins_config/plugins.txt {{ .Values.master.jenkinsHome }};
    rm -rf {{ .Values.master.jenkinsRef }}/plugins/*.lock
    /usr/local/bin/install-plugins.sh `echo $(cat {{ .Values.master.jenkinsHome }}/plugins.txt)`;
    echo "copy plugins to shared volume"
    # Copy plugins to shared volume
    yes n | cp -i {{ .Values.master.jenkinsRef }}/plugins/* /var/jenkins_plugins/;
{{- end }}
{{- if .Values.master.scriptApproval }}
    echo "configure script approval"
  {{- if .Values.master.overwriteConfig }}
    cp /var/jenkins_config/scriptapproval.xml {{ .Values.master.jenkinsHome }}/scriptApproval.xml;
  {{- else }}
    yes n | cp -i /var/jenkins_config/scriptapproval.xml {{ .Values.master.jenkinsHome }}/scriptApproval.xml;
  {{- end }}
{{- end }}
{{- if .Values.master.initScripts }}
    echo "copy init scripts"
    mkdir -p {{ .Values.master.jenkinsHome }}/init.groovy.d/;
    {{- if .Values.master.overwriteConfig }}
    rm -f {{ .Values.master.jenkinsHome }}/init.groovy.d/*.groovy
    {{- end }}
    yes n | cp -i /var/jenkins_config/*.groovy {{ .Values.master.jenkinsHome }}/init.groovy.d/;
{{- end }}
{{- if .Values.master.JCasC.enabled}}
  {{- if not .Values.master.sidecars.configAutoReload.enabled }}
    echo "copy configuration as code files"
    mkdir -p {{ .Values.master.jenkinsHome }}/casc_configs;
    rm -rf {{ .Values.master.jenkinsHome }}/casc_configs/*
    {{- if .Values.master.JCasC.configScripts }}
    cp -v /var/jenkins_config/*.yaml {{ .Values.master.jenkinsHome }}/casc_configs
    {{- end }}
  {{- end }}
{{- end }}
{{- if .Values.master.enableXmlConfig }}
{{- if .Values.master.credentialsXmlSecret }}
    echo "copy credentials.xml"
    yes n | cp -i /var/jenkins_credentials/credentials.xml {{ .Values.master.jenkinsHome }};
{{- end }}
{{- if .Values.master.jobs }}
    echo "copy jobs"
    for job in $(ls /var/jenkins_jobs); do
      mkdir -p {{ .Values.master.jenkinsHome }}/jobs/$job
      yes {{ if not .Values.master.overwriteJobs }}n{{ end }} | cp -i /var/jenkins_jobs/$job {{ .Values.master.jenkinsHome }}/jobs/$job/config.xml
    done
{{- end }}
{{- end }}
{{- if .Values.master.secretsFilesSecret }}
    echo "copy secrets"
    yes n | cp -i /var/jenkins_secrets/* {{ .Values.master.jenkinsRef }}/secrets/;
{{- end }}
    echo "finished initialization"
{{- if .Values.master.initializeOnce }}
    touch {{ .Values.master.jenkinsHome }}/initialization-completed
{{- end }}
{{- range $key, $val := .Values.master.initScripts }}
  init{{ $key }}.groovy: |-
{{ $val | indent 4 }}
{{- end }}
{{- if .Values.master.JCasC.enabled }}
  {{- if not .Values.master.sidecars.configAutoReload.enabled }}
# Only add config to this script if we aren't auto-reloading otherwise the pod will restart upon each config change:
{{- if .Values.master.JCasC.defaultConfig }}
  jcasc-default-config.yaml: |-
    {{- include "jenkins.casc.defaults" . |nindent 4}}
{{- end }}
{{- range $key, $val := .Values.master.JCasC.configScripts }}
  {{ $key }}.yaml: |-
{{ tpl $val $| indent 4 }}
{{- end }}
{{- end }}
{{- end }}
  plugins.txt: |-
{{- if .Values.master.installPlugins }}
  {{- range $installPlugin := .Values.master.installPlugins }}
    {{- $installPlugin | nindent 4 }}
  {{- end }}
  {{- range $addlPlugin := .Values.master.additionalPlugins }}
    {{- /* duplicate plugin check */}}
    {{- range $installPlugin := $.Values.master.installPlugins }}
      {{- if eq (splitList ":" $addlPlugin | first) (splitList ":" $installPlugin | first) }}
        {{- $message := print "[PLUGIN CONFLICT] master.additionalPlugins contains '" $addlPlugin "'" }}
        {{- $message := print $message " but master.installPlugins already contains '" $installPlugin "'." }}
        {{- $message := print $message " Override master.installPlugins to use '" $addlPlugin "' plugin." }}
        {{- fail $message }}
      {{- end }}
    {{- end }}
    {{- $addlPlugin | nindent 4 }}
  {{- end }}
{{- end }}
{{ else }}
{{ include "override_config_map" . }}
{{- end -}}
{{- if .Values.master.additionalConfig }}
{{- toYaml .Values.master.additionalConfig | indent 2 }}
{{- end }}
 # deprecation.yaml
{{- if .Values.checkDeprecation }}
    {{- if .Values.Master }}

        {{- if .Values.Master.Name }}
           {{ fail "`Master.Name` does no longer exist. It has been renamed to `master.componentName`" }}
        {{- end }}

        {{- if .Values.Master.Image }}
           {{ fail "`Master.Image` does no longer exist. It has been renamed to `master.image`" }}
        {{- end }}

        {{- if .Values.Master.ImageTag }}
           {{ fail "`Master.ImageTag` does no longer exist. It has been renamed to `master.tag`" }}
        {{- end }}

        {{- if .Values.Master.ImagePullPolicy }}
           {{ fail "`Master.ImagePullPolicy` does no longer exist. It has been renamed to `master.imagePullPolicy`" }}
        {{- end }}

        {{- if .Values.Master.ImagePullSecret }}
           {{ fail "`Master.ImagePullPolicy` does no longer exist. It has been renamed to `master.imagePullSecretName`" }}
        {{- end }}

        {{- if .Values.Master.Component }}
           {{ fail "`Master.Component` does no longer exist. It has been renamed to `master.componentName`" }}
        {{- end }}

        {{- if .Values.Master.NumExecutors }}
           {{ fail "`Master.NumExecutors` does no longer exist. It has been renamed to `master.numExecutors`" }}
        {{- end }}

        {{- if .Values.Master.UseSecurity }}
           {{ fail "`Master.UseSecurity` does no longer exist. It has been renamed to `master.useSecurity`" }}
        {{- end }}

        {{- if .Values.Master.SecurityRealm }}
           {{ fail "`Master.SecurityRealm` does no longer exist. It has been renamed to `master.securityRealm`" }}
        {{- end }}

        {{- if .Values.Master.AuthorizationStrategy }}
           {{ fail "`Master.AuthorizationStrategy` does no longer exist. It has been renamed to `master.authorizationStrategy`" }}
        {{- end }}

        {{- if .Values.Master.DeploymentLabels }}
           {{ fail "`Master.DeploymentLabels` does no longer exist. It has been renamed to `master.deploymentLabels`" }}
        {{- end }}

        {{- if .Values.Master.ServiceLabels }}
           {{ fail "`Master.ServiceLabels` does no longer exist. It has been renamed to `master.serviceLabels`" }}
        {{- end }}

        {{- if .Values.Master.PodLabels }}
           {{ fail "`Master.PodLabels` does no longer exist. It has been renamed to `master.podLabels`" }}
        {{- end }}

        {{- if .Values.Master.AdminUser }}
           {{ fail "`Master.AdminUser` does no longer exist. It has been renamed to `master.adminUser`" }}
        {{- end }}

        {{- if .Values.Master.AdminPassword }}
           {{ fail "`Master.AdminPassword` does no longer exist. It has been renamed to `master.adminPassword`" }}
        {{- end }}

        {{- if .Values.Master.JenkinsAdminEmail }}
           {{ fail "`Master.JenkinsAdminEmail` does no longer exist. It has been renamed to `master.jenkinsAdminEmail`" }}
        {{- end }}

        {{- if .Values.Master.JenkinsAdminEmail }}
           {{ fail "`Master.JenkinsAdminEmail` does no longer exist. It has been renamed to `master.jenkinsAdminEmail`" }}
        {{- end }}

        {{- if .Values.Master.InitContainerEnv }}
           {{ fail "`Master.InitContainerEnv` does no longer exist. It has been renamed to `master.initContainerEnv`" }}
        {{- end }}

        {{- if .Values.Master.ContainerEnv }}
           {{ fail "`Master.ContainerEnv` does no longer exist. It has been renamed to `master.containerEnv`" }}
        {{- end }}

        {{- if .Values.Master.UsePodSecurityContext }}
           {{ fail "`Master.UsePodSecurityContext` does no longer exist. It has been renamed to `master.usePodSecurityContext`" }}
        {{- end }}

        {{- if .Values.Master.RunAsUser }}
           {{ fail "`Master.RunAsUser` does no longer exist. It has been renamed to `master.runAsUser`" }}
        {{- end }}

        {{- if .Values.Master.FsGroup }}
           {{ fail "`Master.FsGroup` does no longer exist. It has been renamed to `master.fsGroup`" }}
        {{- end }}

        {{- if .Values.Master.HostAliases }}
           {{ fail "`Master.HostAliases` does no longer exist. It has been renamed to `master.hostAliases`" }}
        {{- end }}

        {{- if .Values.Master.ServiceAnnotations }}
           {{ fail "`Master.ServiceAnnotations` does no longer exist. It has been renamed to `master.serviceAnnotations`" }}
        {{- end }}

        {{- if .Values.Master.ServiceType }}
           {{ fail "`Master.ServiceType` does no longer exist. It has been renamed to `master.serviceType`" }}
        {{- end }}

        {{- if .Values.Master.ServicePort }}
           {{ fail "`Master.ServicePort` does no longer exist. It has been renamed to `master.servicePort`" }}
        {{- end }}

        {{- if .Values.Master.NodePort }}
           {{ fail "`Master.NodePort` does no longer exist. It has been renamed to `master.nodePort`" }}
        {{- end }}

        {{- if .Values.Master.HealthProbes }}
           {{ fail "`Master.HealthProbes` does no longer exist. It has been renamed to `master.healthProbes`" }}
        {{- end }}

        {{- if .Values.Master.HealthProbesLivenessTimeout }}
           {{ fail "`Master.HealthProbesLivenessTimeout` does no longer exist. It has been renamed to `master.healthProbesLivenessTimeout`" }}
        {{- end }}

        {{- if .Values.Master.HealthProbesReadinessTimeout }}
           {{ fail "`Master.HealthProbesReadinessTimeout` does no longer exist. It has been renamed to `master.healthProbesReadinessTimeout`" }}
        {{- end }}

        {{- if .Values.Master.HealthProbeReadinessPeriodSeconds }}
           {{ fail "`Master.HealthProbeReadinessPeriodSeconds` does no longer exist. It has been renamed to `master.healthProbeReadinessPeriodSeconds`" }}
        {{- end }}

        {{- if .Values.Master.HealthProbeLivenessFailureThreshold }}
           {{ fail "`Master.HealthProbeLivenessFailureThreshold` does no longer exist. It has been renamed to `master.healthProbeLivenessFailureThreshold`" }}
        {{- end }}

        {{- if .Values.Master.ServiceAnnotations }}
           {{ fail "`Master.ServiceAnnotations` does no longer exist. It has been renamed to `master.serviceAnnotations`" }}
        {{- end }}

        {{- if .Values.Master.SlaveListenerPort }}
           {{ fail "`Master.SlaveListenerPort` does no longer exist. It has been renamed to `master.slaveListenerPort`" }}
        {{- end }}

        {{- if .Values.Master.SlaveHostPort }}
           {{ fail "`Master.SlaveHostPort` does no longer exist. It has been renamed to `master.slaveHostPort`" }}
        {{- end }}

        {{- if .Values.Master.DisabledAgentProtocols }}
           {{ fail "`Master.DisabledAgentProtocols` does no longer exist. It has been renamed to `master.disabledAgentProtocols`" }}
        {{- end }}

        {{- if .Values.Master.CSRF }}
            {{- if .Values.Master.CSRF.DefaultCrumbIssuer.Enabled }}
               {{ fail "`Master.CSRF.DefaultCrumbIssuer.Enabled` does no longer exist. It has been renamed to `master.csrf.defaultCrumbIssuer.enabled`" }}
            {{- end }}

            {{- if .Values.Master.CSRF.DefaultCrumbIssuer.ProxyCompatability }}
               {{ fail "`Master.CSRF.DefaultCrumbIssuer.ProxyCompatability` does no longer exist. It has been renamed to `master.csrf.defaultCrumbIssuer.proxyCompatability`" }}
            {{- end }}
        {{- end }}

        {{- if .Values.Master.CLI }}
           {{ fail "`Master.CLI` does no longer exist. It has been renamed to `master.cli`" }}
        {{- end }}

        {{- if .Values.Master.LoadBalancerSourceRanges }}
           {{ fail "`Master.LoadBalancerSourceRanges` does no longer exist. It has been renamed to `master.loadBalancerSourceRanges`" }}
        {{- end }}

        {{- if .Values.Master.LoadBalancerIP }}
           {{ fail "`Master.LoadBalancerIP` does no longer exist. It has been renamed to `master.loadBalancerIP`" }}
        {{- end }}

        {{- if .Values.Master.JMXPort }}
           {{ fail "`Master.JMXPort` does no longer exist. It has been renamed to `master.jmxPort`" }}
        {{- end }}

        {{- if .Values.Master.ExtraPorts }}
           {{ fail "`Master.ExtraPorts` does no longer exist. It has been renamed to `master.extraPorts`" }}
        {{- end }}

        {{- if .Values.Master.OverwriteConfig }}
           {{ fail "`Master.OverwriteConfig` does no longer exist. It has been renamed to `master.overwriteConfig`" }}
        {{- end }}

        {{- if .Values.JCasC }}
            {{- if .Values.JCasC.ConfigScripts }}
               {{ fail "`Master.JCasC.ConfigScripts` does no longer exist. It has been renamed to `master.JCasC.configScripts`" }}
            {{- end }}
        {{- end }}

        {{- if .Values.Master.Sidecars }}
            {{- if .Values.Master.Sidecars.configAutoReload }}
               {{ fail "`Master.Sidecars.configAutoReload` does no longer exist. It has been renamed to `master.sidecars.configAutoReload`" }}
            {{- end }}
        {{- end }}

        {{- if .Values.Master.InitScripts }}
           {{ fail "`Master.InitScripts` does no longer exist. It has been renamed to `master.initScripts`" }}
        {{- end }}

        {{- if .Values.Master.CredentialsXmlSecret }}
           {{ fail "`Master.CredentialsXmlSecret` does no longer exist. It has been renamed to `master.credentialsXmlSecret`" }}
        {{- end }}

        {{- if .Values.Master.SecretsFilesSecret }}
           {{ fail "`Master.SecretsFilesSecret` does no longer exist. It has been renamed to `master.secretsFilesSecret`" }}
        {{- end }}

        {{- if .Values.Master.CredentialsXmlSecret }}
           {{ fail "`Master.CredentialsXmlSecret` does no longer exist. It has been renamed to `master.credentialsXmlSecret`" }}
        {{- end }}

        {{- if .Values.Master.Jobs }}
           {{ fail "`Master.Jobs` does no longer exist. It has been renamed to `master.jobs`" }}
        {{- end }}

        {{- if .Values.Master.InstallPlugins }}
           {{ fail "`Master.InstallPlugins` does no longer exist. It has been renamed to `master.installPlugins`" }}
        {{- end }}

        {{- if .Values.Master.OverwritePlugins }}
           {{ fail "`Master.OverwritePlugins` does no longer exist. It has been renamed to `master.overwritePlugins`" }}
        {{- end }}

        {{- if .Values.Master.EnableRawHtmlMarkupFormatter }}
           {{ fail "`Master.EnableRawHtmlMarkupFormatter` does no longer exist. It has been renamed to `master.enableRawHtmlMarkupFormatter`" }}
        {{- end }}

        {{- if .Values.Master.ScriptApproval }}
           {{ fail "`Master.ScriptApproval` does no longer exist. It has been renamed to `master.scriptApproval`" }}
        {{- end }}

        {{- if .Values.Master.NodeSelector }}
           {{ fail "`Master.NodeSelector` does no longer exist. It has been renamed to `master.nodeSelector`" }}
        {{- end }}

        {{- if .Values.Master.Affinity }}
           {{ fail "`Master.Affinity` does no longer exist. It has been renamed to `master.affinity`" }}
        {{- end }}

        {{- if .Values.Master.PodAnnotations }}
           {{ fail "`Master.PodAnnotations` does no longer exist. It has been renamed to `master.podAnnotations`" }}
        {{- end }}

        {{- if .Values.Master.CustomConfigMap }}
           {{ fail "`Master.CustomConfigMap` does no longer exist. It has been renamed to `master.customConfigMap`" }}
        {{- end }}

        {{- if .Values.Master.JenkinsUriPrefix }}
           {{ fail "`Master.JenkinsUriPrefix` does no longer exist. It has been renamed to `master.jenkinsUriPrefix`" }}
        {{- end }}

        {{- if .Values.Master.PriorityClassName }}
           {{ fail "`Master.PriorityClassName` does no longer exist. It has been renamed to `master.priorityClassName`" }}
        {{- end }}

        {{ fail "Master.* values have been renamed, please check the documentation" }}
    {{- end }}


    {{- if .Values.NetworkPolicy }}

        {{- if .Values.NetworkPolicy.Enabled }}
           {{ fail "`NetworkPolicy.Enabled` does no longer exist. It has been renamed to `networkPolicy.enabled`" }}
        {{- end }}

        {{- if .Values.NetworkPolicy.ApiVersion }}
           {{ fail "`NetworkPolicy.ApiVersion` does no longer exist. It has been renamed to `networkPolicy.apiVersion`" }}
        {{- end }}

        {{ fail "NetworkPolicy.* values have been renamed, please check the documentation" }}
    {{- end }}


    {{- if .Values.rbac.install }}
       {{ fail "`rbac.install` does no longer exist. It has been renamed to `rbac.create` and is enabled by default!" }}
    {{- end }}

    {{- if .Values.rbac.serviceAccountName }}
       {{ fail "`rbac.serviceAccountName` does no longer exist. It has been renamed to `serviceAccount.name`" }}
    {{- end }}

    {{- if .Values.rbac.serviceAccountAnnotations }}
       {{ fail "`rbac.serviceAccountAnnotations` does no longer exist. It has been renamed to `serviceAccount.annotations`" }}
    {{- end }}

    {{- if .Values.rbac.roleRef }}
       {{ fail "`rbac.roleRef` does no longer exist. RBAC roles are now generated, please check the documentation" }}
    {{- end }}

    {{- if .Values.rbac.roleKind }}
       {{ fail "`rbac.roleKind` does no longer exist. RBAC roles are now generated, please check the documentation" }}
    {{- end }}

    {{- if .Values.rbac.roleBindingKind }}
       {{ fail "`rbac.roleBindingKind` does no longer exist. RBAC roles are now generated, please check the documentation" }}
    {{- end }}


    {{- if .Values.Agent }}
        {{- if .Values.Agent.AlwaysPullImage }}
           {{ fail "`Agent.AlwaysPullImage` does no longer exist. It has been renamed to `agent.alwaysPullImage`" }}
        {{- end }}

        {{- if .Values.Agent.CustomJenkinsLabels }}
           {{ fail "`Agent.CustomJenkinsLabels` does no longer exist. It has been renamed to `agent.customJenkinsLabels`" }}
        {{- end }}

        {{- if .Values.Agent.Enabled }}
           {{ fail "`Agent.Enabled` does no longer exist. It has been renamed to `agent.enabled`" }}
        {{- end }}

        {{- if .Values.Agent.Image }}
           {{ fail "`Agent.Image` does no longer exist. It has been renamed to `agent.image`" }}
        {{- end }}

        {{- if .Values.Agent.ImagePullSecret }}
           {{ fail "`Agent.ImagePullSecret` does no longer exist. It has been renamed to `agent.imagePullSecret`" }}
        {{- end }}

        {{- if .Values.Agent.ImageTag }}
           {{ fail "`Agent.ImageTag` does no longer exist. It has been renamed to `agent.imageTag`" }}
        {{- end }}

        {{- if .Values.Agent.Privileged }}
           {{ fail "`Agent.Privileged` does no longer exist. It has been renamed to `agent.privileged`" }}
        {{- end }}

        {{- if .Values.Agent.Command }}
           {{ fail "`Agent.Command` does no longer exist. It has been renamed to `agent.command`" }}
        {{- end }}

        {{- if .Values.Agent.Args }}
           {{ fail "`Agent.Args` does no longer exist. It has been renamed to `agent.args`" }}
        {{- end }}

        {{- if .Values.Agent.SideContainerName }}
           {{ fail "`Agent.SideContainerName` does no longer exist. It has been renamed to `agent.sideContainerName`" }}
        {{- end }}

        {{- if .Values.Agent.ContainerCap }}
           {{ fail "`Agent.ContainerCap` does no longer exist. It has been renamed to `agent.containerCap`" }}
        {{- end }}

        {{- if .Values.Agent.PodName }}
           {{ fail "`Agent.PodName` does no longer exist. It has been renamed to `agent.podName`" }}
        {{- end }}

       {{ fail "Agent.* values have been renamed, please check the documentation" }}
    {{- end }}

    {{- if .Values.Persistence }}
       {{ fail "Persistence.* values have been renamed, please check the documentation" }}
    {{- end }}

    {{- if .Values.master.JCasC.pluginVersion }}
       {{ fail "master.JCasC.pluginVersion has been deprecated, please use master.installPlugins instead" }}
    {{- end }}
{{- end }}
 # home-pvc.yaml
{{- if not (contains "jenkins-home" (quote .Values.persistence.volumes)) }}
{{- if and .Values.persistence.enabled (not .Values.persistence.existingClaim) -}}
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
{{- if .Values.persistence.annotations }}
  annotations:
{{ toYaml .Values.persistence.annotations | indent 4 }}
{{- end }}
  name: {{ template "jenkins.fullname" . }}
  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:
  accessModes:
    - {{ .Values.persistence.accessMode | quote }}
  resources:
    requests:
      storage: {{ .Values.persistence.size | quote }}
{{- if .Values.persistence.storageClass }}
{{- if (eq "-" .Values.persistence.storageClass) }}
  storageClassName: ""
{{- else }}
  storageClassName: "{{ .Values.persistence.storageClass }}"
{{- end }}
{{- end }}
{{- end }}
{{- end }}
 # jcasc-config.yaml
{{- $root := . }}
{{- if and (.Values.master.JCasC.enabled) (.Values.master.sidecars.configAutoReload.enabled) }}
{{- range $key, $val := .Values.master.JCasC.configScripts }}
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "jenkins.fullname" $root }}-jenkins-config-{{ $key }}
  namespace: {{ template "jenkins.namespace" $root }}
  labels:
    "app.kubernetes.io/name": {{ template "jenkins.name" $root}}
    "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 }}"
    {{ template "jenkins.fullname" $root }}-jenkins-config: "true"
data:
  {{ $key }}.yaml: |-
{{ tpl $val $| indent 4 }}
{{- end }}
{{- if .Values.master.JCasC.defaultConfig }}
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "jenkins.fullname" $root }}-jenkins-jcasc-config
  namespace: {{ template "jenkins.namespace" $root }}
  labels:
    "app.kubernetes.io/name": {{ template "jenkins.name" $root}}
    "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 }}"
    {{ template "jenkins.fullname" $root }}-jenkins-config: "true"
data:
  jcasc-default-config.yaml: |-
    {{- include "jenkins.casc.defaults" . |nindent 4 }}
{{- end}}
{{- end }}
 # jenkins-agent-svc.yaml
apiVersion: v1
kind: Service
metadata:
  name: {{ template "jenkins.fullname" . }}-agent
  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 }}"
{{- if .Values.master.slaveListenerServiceAnnotations }}
  annotations:
{{ toYaml .Values.master.slaveListenerServiceAnnotations | indent 4 }}
{{- end }}
spec:
  ports:
    - port: {{ .Values.master.slaveListenerPort }}
      targetPort: {{ .Values.master.slaveListenerPort }}
      {{ if (and (eq .Values.master.slaveListenerServiceType "NodePort") (not (empty .Values.master.slaveListenerPort))) }}
      nodePort: {{.Values.master.slaveListenerPort}}
      {{end}}
      name: slavelistener
  selector:
    "app.kubernetes.io/component": "{{ .Values.master.componentName }}"
    "app.kubernetes.io/instance": "{{ .Release.Name }}"
  type: {{ .Values.master.slaveListenerServiceType }}
  {{  if eq .Values.master.slaveListenerServiceType "LoadBalancer"  }}
  {{  if .Values.master.slaveListenerLoadBalancerIP  }}
  loadBalancerIP: {{  .Values.master.slaveListenerLoadBalancerIP  }}
  {{end}}
  {{end}}
 # jenkins-backup-cronjob.yaml
{{- if .Values.backup.enabled }}
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: {{ template "jenkins.fullname" . }}-backup
  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.backup.componentName }}"
spec:
  schedule: {{ .Values.backup.schedule | quote }}
  concurrencyPolicy: Forbid
  startingDeadlineSeconds: 120
  jobTemplate:
    spec:
      template:
        metadata:
          {{- if .Values.backup.labels }}
          labels:
{{ toYaml .Values.backup.labels | trim | indent 12 }}
          {{- end }}
          {{- if .Values.backup.annotations }}
          annotations:
{{ toYaml .Values.backup.annotations | trim | indent 12 }}
          {{- end }}
        spec:
          restartPolicy: OnFailure
          serviceAccountName: {{ template "jenkins.fullname" . }}-backup
          containers:
          - name: jenkins-backup
            image: "{{ .Values.backup.image.repository }}:{{ .Values.backup.image.tag }}"
            command: ["kube-tasks"]
            args:
            - simple-backup
            - -n
            - {{ template "jenkins.namespace" . }}
            - -l
            - app.kubernetes.io/instance={{ .Release.Name }}
            - --container
            - jenkins
            - --path
            - {{ .Values.master.jenkinsHome }}
            - --dst
            - {{ .Values.backup.destination }}
            {{- with .Values.backup.extraArgs }}
{{ toYaml . | indent 12 }}
            {{- end }}
            env:
            {{- with .Values.backup.env }}
{{ toYaml . | trim | indent 12 }}
            {{- end }}
            {{- if .Values.backup.existingSecret }}
            {{- range $key,$value := .Values.backup.existingSecret }}
            {{- if $value.awsaccesskey }}
            - name: AWS_ACCESS_KEY_ID
              valueFrom:
                secretKeyRef:
                  name: {{ $key }}
                  key: {{ $value.awsaccesskey | quote }}
            {{- end }}
            {{- if $value.awssecretkey }}
            - name: AWS_SECRET_ACCESS_KEY
              valueFrom:
                secretKeyRef:
                  name: {{ $key }}
                  key: {{ $value.awssecretkey | quote}}
            {{- end }}
            {{- if $value.gcpcredentials }}
            - name: GOOGLE_APPLICATION_CREDENTIALS
              value: "/var/run/secrets/{{ $key }}/{{ $value.gcpcredentials }}"
            {{- end }}
            {{- end }}
            {{- end }}
          {{- with .Values.backup.resources }}
            resources:
{{ toYaml . | trim | indent 14 }}
          {{- end }}
            volumeMounts:
          {{- if .Values.backup.existingSecret }}
          {{- range $key,$value := .Values.backup.existingSecret }}
          {{- if $value.gcpcredentials }}
            - mountPath: /var/run/secrets/{{ $key }}
              name: {{ $key }}
          {{- end }}
          {{- end }}
          {{- end }}
          volumes:
          {{- if .Values.backup.existingSecret }}
          {{- range $key,$value := .Values.backup.existingSecret }}
          {{- if $value.gcpcredentials }}
          - name:  {{ $key }}
            secret:
              secretName:  {{ $key }}
          {{- end }}
          {{- end }}
          {{- end }}
          affinity:
            podAffinity:
              preferredDuringSchedulingIgnoredDuringExecution:
              - weight: 100
                podAffinityTerm:
                  topologyKey: "kubernetes.io/hostname"
                  labelSelector:
                    matchExpressions:
                    - key: app
                      operator: In
                      values:
                      - {{ template "jenkins.fullname" . }}
                    - key: release
                      operator: In
                      values:
                      - {{ .Release.Name }}
      {{- with .Values.tolerations }}
          tolerations:
{{ toYaml . | indent 10 }}
      {{- end }}
{{- end }}
 # jenkins-backup-rbac.yaml
{{- if .Values.backup.enabled }}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ template "jenkins.fullname" . }}-backup
  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 }}"
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: {{ template "jenkins.fullname" . }}-backup
  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 }}"
rules:
- apiGroups: [""]
  resources: ["pods", "pods/log"]
  verbs: ["get", "list"]
- apiGroups: [""]
  resources: ["pods/exec"]
  verbs: ["create"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: {{ template "jenkins.fullname" . }}-backup
  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 }}"
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: {{ template "jenkins.fullname" . }}-backup
subjects:
- kind: ServiceAccount
  name: {{ template "jenkins.fullname" . }}-backup
  namespace: {{ template "jenkins.namespace" . }}
{{- end }}
 # jenkins-master-alerting-rules.yaml
{{- if and .Values.master.prometheus.enabled .Values.master.prometheus.alertingrules }}
---
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: {{ template "jenkins.fullname" . }}
  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 }}"
    {{- range $key, $val := .Values.master.prometheus.alertingRulesAdditionalLabels }}
    {{ $key }}: {{ $val | quote }}
    {{- end}}
spec:
  groups:
{{ toYaml .Values.master.prometheus.alertingrules | indent 2 }}
{{- end }}
 # jenkins-master-backendconfig.yaml
{{- if .Values.master.backendconfig.enabled }}
apiVersion: {{ .Values.master.backendconfig.apiVersion }}
kind: BackendConfig
metadata:
  name: {{ .Values.master.backendconfig.name }}
  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 }}"
{{- if .Values.master.backendconfig.labels }}
{{ toYaml .Values.master.backendconfig.labels | indent 4 }}
{{- end }}
{{- if .Values.master.backendconfig.annotations }}
  annotations:
{{ toYaml .Values.master.backendconfig.annotations | indent 4 }}
{{- end }}
spec:
{{ toYaml .Values.master.backendconfig.spec | indent 2 }}
{{- end }}
 # jenkins-master-deployment.yaml
{{- if .Capabilities.APIVersions.Has "apps/v1" }}
apiVersion: apps/v1
{{- else }}
apiVersion: apps/v1beta1
{{- end }}
kind: Deployment
metadata:
  name: {{ template "jenkins.fullname" . }}
  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 }}"
    {{- range $key, $val := .Values.master.deploymentLabels }}
    {{ $key }}: {{ $val | quote }}
    {{- end}}
  {{- if .Values.master.deploymentAnnotations }}
  annotations:
{{ toYaml .Values.master.deploymentAnnotations | indent 4 }}
  {{- end }}
spec:
  replicas: 1
  strategy:
    type: {{ if .Values.persistence.enabled }}Recreate{{ else }}RollingUpdate
    rollingUpdate:
{{ toYaml .Values.master.rollingUpdate | indent 6 }}
    {{- end }}
  selector:
    matchLabels:
      "app.kubernetes.io/component": "{{ .Values.master.componentName }}"
      "app.kubernetes.io/instance": "{{ .Release.Name }}"
  template:
    metadata:
      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 }}"
        {{- range $key, $val := .Values.master.podLabels }}
        {{ $key }}: {{ $val | quote }}
        {{- end}}
      annotations:
        checksum/config: {{ include (print $.Template.BasePath "/config.yaml") . | sha256sum }}
        {{- if .Values.master.podAnnotations }}
{{ toYaml .Values.master.podAnnotations | indent 8 }}
        {{- end }}
    spec:
      {{- if .Values.master.schedulerName }}
      schedulerName: {{ .Values.master.schedulerName }}
      {{- end }}
      {{- if .Values.master.nodeSelector }}
      nodeSelector:
{{ toYaml .Values.master.nodeSelector | indent 8 }}
      {{- end }}
      {{- if .Values.master.tolerations }}
      tolerations:
{{ toYaml .Values.master.tolerations | indent 8 }}
      {{- end }}
      {{- if .Values.master.affinity }}
      affinity:
{{ toYaml .Values.master.affinity | indent 8 }}
      {{- end }}
      {{- if quote .Values.master.terminationGracePeriodSeconds }}
      terminationGracePeriodSeconds: {{ .Values.master.terminationGracePeriodSeconds }}
      {{- end }}
      {{- if and (.Capabilities.APIVersions.Has "scheduling.k8s.io/v1beta1") (.Values.master.priorityClassName) }}
      priorityClassName: {{ .Values.master.priorityClassName }}
      {{- end }}
{{- if .Values.master.usePodSecurityContext }}
      securityContext:
        runAsUser: {{ default 0 .Values.master.runAsUser }}
{{- if and (.Values.master.runAsUser) (.Values.master.fsGroup) }}
{{- if not (eq (int .Values.master.runAsUser) 0) }}
        fsGroup: {{ .Values.master.fsGroup }}
{{- end }}
{{- end }}
{{- end }}
      serviceAccountName: "{{ template "jenkins.serviceAccountName" . }}"
{{- if .Values.master.hostNetworking }}
      hostNetwork: true
      dnsPolicy: ClusterFirstWithHostNet
{{- end }}
      {{- if .Values.master.hostAliases }}
      hostAliases:
        {{- toYaml .Values.master.hostAliases | nindent 8 }}
      {{- end }}
      initContainers:
{{- if .Values.master.customInitContainers }}
{{ tpl (toYaml .Values.master.customInitContainers) . | indent 8 }}
{{- end }}
        - name: "copy-default-config"
{{- if .Values.master.imageTag }}
          image: "{{ .Values.master.image }}:{{ .Values.master.imageTag }}"
{{- else }}
          image: "{{ .Values.master.image }}:{{ .Values.master.tag }}"
{{- end }}
          imagePullPolicy: "{{ .Values.master.imagePullPolicy }}"
          command: [ "sh", "/var/jenkins_config/apply_config.sh" ]
          env:
          {{- if .Values.master.useSecurity }}
            - name: ADMIN_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ .Values.master.admin.existingSecret | default (include "jenkins.fullname" .) }}
                  key: {{ .Values.master.admin.passwordKey | default "jenkins-admin-password" }}
            - name: ADMIN_USER
              valueFrom:
                secretKeyRef:
                  name: {{ .Values.master.admin.existingSecret | default (include "jenkins.fullname" .) }}
                  key: {{ .Values.master.admin.userKey | default "jenkins-admin-user" }}
            {{- end }}
            {{- if .Values.master.initContainerEnv }}
{{ toYaml .Values.master.initContainerEnv | indent 12 }}
            {{- end }}
          resources:
{{ toYaml .Values.master.resources | indent 12 }}
          volumeMounts:
            - mountPath: /tmp
              name: tmp
            - mountPath: {{ .Values.master.jenkinsHome }}
              name: jenkins-home
              {{- if .Values.persistence.subPath }}
              subPath: {{ .Values.persistence.subPath }}
              {{- end }}
            - mountPath: /var/jenkins_config
              name: jenkins-config
            {{- if .Values.master.enableXmlConfig }}
            {{- if .Values.master.credentialsXmlSecret }}
            - mountPath: /var/jenkins_credentials
              name: jenkins-credentials
              readOnly: true
            {{- end }}
            {{- if .Values.master.jobs }}
            - mountPath: /var/jenkins_jobs
              name: jenkins-jobs
              readOnly: true
            {{- end }}
            {{- end }}
            - mountPath: {{ .Values.master.jenkinsRef }}/secrets/
              name: secrets-dir
            {{- if .Values.master.secretsFilesSecret }}
            - mountPath: /var/jenkins_secrets
              name: jenkins-secrets
              readOnly: true
            {{- end }}
            {{- if .Values.master.installPlugins }}
            {{- if .Values.master.overwritePluginsFromImage }}
            - mountPath: {{ .Values.master.jenkinsRef }}/plugins
              name: plugins
            {{- end }}
            - mountPath: /var/jenkins_plugins
              name: plugin-dir
            {{- end }}
      containers:
        - name: jenkins
{{- if .Values.master.imageTag }}
          image: "{{ .Values.master.image }}:{{ .Values.master.imageTag }}"
{{- else }}
          image: "{{ .Values.master.image }}:{{ .Values.master.tag }}"
{{- end }}
          imagePullPolicy: "{{ .Values.master.imagePullPolicy }}"
          {{- if .Values.master.httpsKeyStore.enable }}
          {{- $httpsJKSFilePath :=  printf "%s/%s" .Values.master.httpsKeyStore.path .Values.master.httpsKeyStore.fileName -}}
              {{- if .Values.master.useSecurity }}
          args: [ "--argumentsRealm.passwd.$(ADMIN_USER)=$(ADMIN_PASSWORD)",  "--argumentsRealm.roles.$(ADMIN_USER)=admin", "--httpPort={{.Values.master.httpsKeyStore.httpPort}}", "--httpsPort={{.Values.master.targetPort}}", '--httpsKeyStore={{ $httpsJKSFilePath }}', "--httpsKeyStorePassword=$(JENKINS_HTTPS_KEYSTORE_PASSWORD)" ]
              {{- else }}
          args: [ "--httpPort={{.Values.master.httpsKeyStore.httpPort}}", "--httpsPort={{.Values.master.targetPort}}", '--httpsKeyStore={{ $httpsJKSFilePath | quote }}', "--httpsKeyStorePassword=$(JENKINS_HTTPS_KEYSTORE_PASSWORD)" ]
              {{- end }}
          {{- else if .Values.master.useSecurity }}
          args: [ "--argumentsRealm.passwd.$(ADMIN_USER)=$(ADMIN_PASSWORD)",  "--argumentsRealm.roles.$(ADMIN_USER)=admin", "--httpPort={{.Values.master.targetPort}}"]
          {{- end }}
          {{- if .Values.master.lifecycle }}
          lifecycle:
{{ toYaml .Values.master.lifecycle | indent 12 }}
          {{- end }}
          env:
            - name: POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: JAVA_OPTS
              value: >
                {{ default "" .Values.master.javaOpts }}
                {{ if .Values.master.sidecars.configAutoReload.enabled }} -Dcasc.reload.token=$(POD_NAME) {{ end }}
            - name: JENKINS_OPTS
              value: "{{ if .Values.master.jenkinsUriPrefix }}--prefix={{ .Values.master.jenkinsUriPrefix }} {{ end }}{{ default "" .Values.master.jenkinsOpts}}"
            - name: JENKINS_SLAVE_AGENT_PORT
              value: "{{ .Values.master.slaveListenerPort }}"
            {{- if .Values.master.useSecurity }}
            - name: ADMIN_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ .Values.master.admin.existingSecret | default (include "jenkins.fullname" .) }}
                  key: {{ .Values.master.admin.password | default "jenkins-admin-password" }}
            - name: ADMIN_USER
              valueFrom:
                secretKeyRef:
                  name: {{ .Values.master.admin.existingSecret | default (include "jenkins.fullname" .) }}
                  key: {{ .Values.master.admin.user | default "jenkins-admin-user" }}
            {{- end }}
            {{- if .Values.master.httpsKeyStore.enable }}
            - name: JENKINS_HTTPS_KEYSTORE_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ if .Values.master.httpsKeyStore.jenkinsHttpsJksSecretName }} {{ .Values.master.httpsKeyStore.jenkinsHttpsJksSecretName }} {{ else }} {{ template "jenkins.fullname" . }}-https-jks  {{ end }}
                  key: {{ "https-jks-password" | quote }}
            {{- end }}

            {{- if .Values.master.containerEnv }}
{{ toYaml .Values.master.containerEnv | indent 12 }}
            {{- end }}
            {{- if .Values.master.JCasC.enabled }}
            - name: CASC_JENKINS_CONFIG
              value: {{ .Values.master.sidecars.configAutoReload.folder | default (printf "%s/casc_configs" (.Values.master.jenkinsRef)) }}
            {{- end }}
          ports:
            {{- if .Values.master.httpsKeyStore.enable }}
            - containerPort: {{.Values.master.httpsKeyStore.httpPort}}
            {{- else }}
            - containerPort: {{.Values.master.targetPort}}
            {{- end }}
              name: http
            - containerPort: {{ .Values.master.slaveListenerPort }}
              name: slavelistener
              {{- if .Values.master.slaveHostPort }}
              hostPort: {{ .Values.master.slaveHostPort }}
              {{- end }}
            {{- if .Values.master.jmxPort }}
            - containerPort: {{ .Values.master.jmxPort }}
              name: jmx
            {{- end }}
{{- range $index, $port := .Values.master.extraPorts }}
            - containerPort: {{ $port.port }}
              name: {{ $port.name }}
{{- end }}
{{- if .Values.master.healthProbes }}
          livenessProbe:
            httpGet:
              path: "{{ default "" .Values.master.jenkinsUriPrefix }}/login"
              port: http
            initialDelaySeconds: {{ .Values.master.healthProbeLivenessInitialDelay }}
            periodSeconds: {{ .Values.master.healthProbeLivenessPeriodSeconds }}
            timeoutSeconds: {{ .Values.master.healthProbesLivenessTimeout }}
            failureThreshold: {{ .Values.master.healthProbeLivenessFailureThreshold }}
          readinessProbe:
            httpGet:
              path: "{{ default "" .Values.master.jenkinsUriPrefix }}/login"
              port: http
            initialDelaySeconds: {{ .Values.master.healthProbeReadinessInitialDelay }}
            periodSeconds: {{ .Values.master.healthProbeReadinessPeriodSeconds }}
            timeoutSeconds: {{ .Values.master.healthProbesReadinessTimeout }}
            failureThreshold: {{ .Values.master.healthProbeReadinessFailureThreshold }}
{{- end }}

          resources:
{{ toYaml .Values.master.resources | indent 12 }}
          volumeMounts:
{{- if .Values.persistence.mounts }}
{{ toYaml .Values.persistence.mounts | indent 12 }}
{{- end }}
            {{- if .Values.master.httpsKeyStore.enable }}
            - mountPath: {{ .Values.master.httpsKeyStore.path }}
              name: jenkins-https-keystore
            {{- end }}
            - mountPath: /tmp
              name: tmp
            - mountPath: {{ .Values.master.jenkinsHome }}
              name: jenkins-home
              readOnly: false
              {{- if .Values.persistence.subPath }}
              subPath: {{ .Values.persistence.subPath }}
              {{- end }}
            - mountPath: /var/jenkins_config
              name: jenkins-config
              readOnly: true
            {{- if .Values.master.enableXmlConfig }}
            {{- if .Values.master.credentialsXmlSecret }}
            - mountPath: /var/jenkins_credentials
              name: jenkins-credentials
              readOnly: true
            {{- end }}
            {{- if .Values.master.jobs }}
            - mountPath: /var/jenkins_jobs
              name: jenkins-jobs
              readOnly: true
            {{- end }}
            {{- end }}
            - mountPath: {{ .Values.master.jenkinsRef }}/secrets/
              name: secrets-dir
              readOnly: false
            {{- if or .Values.master.secretsFilesSecret }}
            - mountPath: /var/jenkins_secrets
              name: jenkins-secrets
              readOnly: true
            {{- end }}
            {{- if .Values.master.installPlugins }}
            - mountPath: {{ .Values.master.jenkinsRef }}/plugins/
              name: plugin-dir
              readOnly: false
            {{- end }}
            {{- if and (.Values.master.JCasC.enabled) (.Values.master.sidecars.configAutoReload.enabled) }}
            - name: sc-config-volume
              mountPath: {{ .Values.master.sidecars.configAutoReload.folder | default (printf "%s/casc_configs" (.Values.master.jenkinsRef)) }}
            {{- end }}

{{- if and (.Values.master.JCasC.enabled) (.Values.master.sidecars.configAutoReload.enabled) }}
        - name: jenkins-sc-config
          image: "{{ .Values.master.sidecars.configAutoReload.image }}"
          imagePullPolicy: {{ .Values.master.sidecars.configAutoReload.imagePullPolicy }}
          env:
            - name: POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: LABEL
              value: "{{ template "jenkins.fullname" . }}-jenkins-config"
            - name: FOLDER
              value: "{{ .Values.master.sidecars.configAutoReload.folder }}"
            - name: NAMESPACE
              value: "{{ .Values.master.sidecars.configAutoReload.searchNamespace | default .Release.Namespace }}"
            - name: REQ_URL
              value: "http://localhost:8080{{- .Values.master.jenkinsUriPrefix -}}/reload-configuration-as-code/?casc-reload-token=$(POD_NAME)"
            - name: REQ_METHOD
              value: "POST"
            - name: REQ_RETRY_CONNECT
              value: "{{ .Values.master.sidecars.configAutoReload.reqRetryConnect }}"
            {{- if .Values.master.sidecars.configAutoReload.env }}
{{ toYaml .Values.master.sidecars.configAutoReload.env | indent 12 }}
            {{- end }}
          resources:
{{ toYaml .Values.master.sidecars.configAutoReload.resources | indent 12 }}
          volumeMounts:
            - name: sc-config-volume
              mountPath: {{ .Values.master.sidecars.configAutoReload.folder | quote }}
            - name: jenkins-home
              mountPath: {{ .Values.master.jenkinsHome }}
              {{- if .Values.persistence.subPath }}
              subPath: {{ .Values.persistence.subPath }}
              {{- end }}
{{- end}}


{{- if .Values.master.sidecars.other}}
{{ tpl (toYaml .Values.master.sidecars.other | indent 8) .}}
{{- end }}

      volumes:
{{- if .Values.persistence.volumes }}
{{ tpl (toYaml .Values.persistence.volumes | indent 6) . }}
{{- end }}
      - name: plugins
        emptyDir: {}
      - name: tmp
        emptyDir: {}
      - name: jenkins-config
        configMap:
          name: {{ template "jenkins.fullname" . }}
      {{- if .Values.master.enableXmlConfig }}
      {{- if .Values.master.credentialsXmlSecret }}
      - name: jenkins-credentials
        secret:
          secretName: {{ .Values.master.credentialsXmlSecret }}
      {{- end }}
      {{- if .Values.master.jobs }}
      - name: jenkins-jobs
        configMap:
          name: {{ template "jenkins.fullname" . }}-jobs
      {{- end }}
      {{- end }}
      - name: secrets-dir
        emptyDir: {}
      {{- if .Values.master.secretsFilesSecret }}
      - name: jenkins-secrets
        secret:
          secretName: {{ .Values.master.secretsFilesSecret }}
      {{- end }}
      {{- if .Values.master.installPlugins }}
      - name: plugin-dir
        emptyDir: {}
      {{- end }}
      {{- if not (contains "jenkins-home" (quote .Values.persistence.volumes)) }}
      - name: jenkins-home
      {{- if .Values.persistence.enabled }}
        persistentVolumeClaim:
          claimName: {{ .Values.persistence.existingClaim | default (include "jenkins.fullname" .) }}
      {{- else }}
        emptyDir: {}
      {{- end -}}
      {{- end -}}
      {{- if .Values.master.JCasC.enabled }}
      - name: sc-config-volume
        emptyDir: {}
      {{- end }}

      {{- if .Values.master.httpsKeyStore.enable }}
      - name: jenkins-https-keystore
        secret:
          secretName: {{ if .Values.master.httpsKeyStore.jenkinsHttpsJksSecretName }} {{ .Values.master.httpsKeyStore.jenkinsHttpsJksSecretName }} {{ else }} {{ template "jenkins.fullname" . }}-https-jks  {{ end }}
          items:
          - key: jenkins-jks-file
            path: {{ .Values.master.httpsKeyStore.fileName }}
      {{- end }}

{{- if .Values.master.imagePullSecretName }}
      imagePullSecrets:
      - name: {{ .Values.master.imagePullSecretName }}
{{- end -}}
 # jenkins-master-ingress.yaml
{{- if .Values.master.ingress.enabled }}
{{- if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion -}}
apiVersion: networking.k8s.io/v1beta1
{{- else -}}
apiVersion: {{ .Values.master.ingress.apiVersion }}
{{- end }}
kind: Ingress
metadata:
  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 }}"
{{- if .Values.master.ingress.labels }}
{{ toYaml .Values.master.ingress.labels | indent 4 }}
{{- end }}
{{- if .Values.master.ingress.annotations }}
  annotations:
{{ toYaml .Values.master.ingress.annotations | indent 4 }}
{{- end }}
  name: {{ template "jenkins.fullname" . }}
spec:
  rules:
  - http:
      paths:
{{- if len (.Values.master.ingress.paths) }}
{{ tpl (toYaml .Values.master.ingress.paths | indent 6) . }}
{{- else }}
      - backend:
          serviceName: {{ template "jenkins.fullname" . }}
          servicePort: {{ .Values.master.servicePort }}
{{- if .Values.master.ingress.path }}
        path: {{ .Values.master.ingress.path }}
{{- end -}}
{{- end -}}
{{- if .Values.master.ingress.hostName }}
    host: {{ .Values.master.ingress.hostName | quote }}
{{- end }}
{{- if .Values.master.ingress.resourceRootUrl }}
  - http:
      paths:
      - backend:
          serviceName: {{ template "jenkins.fullname" . }}
          servicePort: {{ .Values.master.servicePort }}
    host: {{ .Values.master.ingress.resourceRootUrl | quote }}
{{- end }}
{{- if .Values.master.ingress.tls }}
  tls:
{{ toYaml .Values.master.ingress.tls | indent 4 }}
{{- end -}}
{{- end }}
 # 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 }}
 # jenkins-master-route.yaml
{{- if .Values.master.route.enabled }}
apiVersion: route.openshift.io/v1
kind: Route
metadata:
  namespace: {{ template "jenkins.namespace" . }}
  labels:
    app: {{ template "jenkins.fullname" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    release: "{{ .Release.Name }}"
    heritage: "{{ .Release.Service }}"
    component: "{{ .Release.Name }}-{{ .Values.master.componentName }}"
{{- if .Values.master.route.labels }}
{{ toYaml .Values.master.route.labels | indent 4 }}
{{- end }}
{{- if .Values.master.route.annotations }}
  annotations:
{{ toYaml .Values.master.route.annotations | indent 4 }}
{{- end }}
  name: {{ template "jenkins.fullname" . }}
spec:
  host: {{ .Values.master.route.path }}
  port:
    targetPort: http
  tls:
    insecureEdgeTerminationPolicy: Redirect
    termination: edge
  to:
    kind: Service
    name: {{ template "jenkins.fullname" . }}
    weight: 100
  wildcardPolicy: None
{{- end }}
 # jenkins-master-servicemonitor.yaml
{{- if and .Values.master.prometheus.enabled }}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor

metadata:
  name: {{ template "jenkins.fullname" . }}
{{- if .Values.master.prometheus.serviceMonitorNamespace }}
  namespace: {{ .Values.master.prometheus.serviceMonitorNamespace }}
{{- else }}
  namespace: {{ template "jenkins.namespace" . }}
{{- end }}
  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 }}"
    {{- range $key, $val := .Values.master.prometheus.serviceMonitorAdditionalLabels }}
    {{ $key }}: {{ $val | quote }}
    {{- end}}

spec:
  endpoints:
  - interval: {{ .Values.master.prometheus.scrapeInterval }}
    port: http
    path: {{ .Values.master.jenkinsUriPrefix }}{{ .Values.master.prometheus.scrapeEndpoint }}
  jobLabel: {{ template "jenkins.fullname" . }}
  namespaceSelector:
    matchNames:
    - "{{ template "jenkins.namespace" $ }}"
  selector:
    matchLabels:
      "app.kubernetes.io/name": '{{ template "jenkins.name" .}}'
      "helm.sh/chart": "{{ .Chart.Name }}-{{ .Chart.Version }}"
      "app.kubernetes.io/instance": "{{ .Release.Name }}"
      "app.kubernetes.io/component": "{{ .Values.master.componentName }}"
{{- end }}
 # jenkins-master-svc.yaml
apiVersion: v1
kind: Service
metadata:
  name: {{template "jenkins.fullname" . }}
  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 }}"
    {{- if .Values.master.serviceLabels }}
{{ toYaml .Values.master.serviceLabels | indent 4 }}
    {{- end }}
{{- if .Values.master.serviceAnnotations }}
  annotations:
{{ toYaml .Values.master.serviceAnnotations | indent 4 }}
{{- end }}
spec:
  {{- if (and (eq .Values.master.serviceType "ClusterIP") (not (empty .Values.master.clusterIP))) }}
  clusterIP: {{.Values.master.clusterIP}}
  {{- end }}
  ports:
    - port: {{.Values.master.servicePort}}
      name: http
      targetPort: {{ .Values.master.targetPort }}
      {{- if (and (eq .Values.master.serviceType "NodePort") (not (empty .Values.master.nodePort))) }}
      nodePort: {{.Values.master.nodePort}}
      {{- end }}
{{- range $index, $port := .Values.master.extraPorts }}
    - port: {{ $port.port }}
      name: {{ $port.name }}
      targetPort: {{ $port.port }}
{{- end }}
  selector:
    "app.kubernetes.io/component": "{{ .Values.master.componentName }}"
    "app.kubernetes.io/instance": "{{ .Release.Name }}"
  type: {{.Values.master.serviceType}}
  {{if eq .Values.master.serviceType "LoadBalancer"}}
{{- if .Values.master.loadBalancerSourceRanges }}
  loadBalancerSourceRanges:
{{ toYaml .Values.master.loadBalancerSourceRanges | indent 4 }}
{{- end }}
  {{if .Values.master.loadBalancerIP}}
  loadBalancerIP: {{.Values.master.loadBalancerIP}}
  {{end}}
  {{end}}
 # jenkins-test.yaml
{{- if .Values.master.testEnabled }}
apiVersion: v1
kind: Pod
metadata:
  name: "{{ .Release.Name }}-ui-test-{{ randAlphaNum 5 | lower }}"
  namespace: {{ template "jenkins.namespace" . }}
  annotations:
    "helm.sh/hook": test-success
spec:
  {{- if .Values.master.nodeSelector }}
  nodeSelector:
{{ toYaml .Values.master.nodeSelector | indent 4 }}
  {{- end }}
  {{- if .Values.master.tolerations }}
  tolerations:
{{ toYaml .Values.master.tolerations | indent 4 }}
  {{- end }}
  initContainers:
    - name: "test-framework"
      image: "dduportal/bats:0.4.0"
      command:
      - "bash"
      - "-c"
      - |
        set -ex
        # copy bats to tools dir
        cp -R /usr/local/libexec/ /tools/bats/
      volumeMounts:
      - mountPath: /tools
        name: tools
  containers:
    - name: {{ .Release.Name }}-ui-test
{{- if .Values.master.imageTag }}
      image: {{ .Values.master.image }}:{{ .Values.master.imageTag }}
{{- else }}
      image: {{ .Values.master.image }}:{{ .Values.master.tag }}
{{- end }}
      command: ["/tools/bats/bats", "-t", "/tests/run.sh"]
      volumeMounts:
      - mountPath: /tests
        name: tests
        readOnly: true
      - mountPath: /tools
        name: tools
  volumes:
  - name: tests
    configMap:
      name: {{ template "jenkins.fullname" . }}-tests
  - name: tools
    emptyDir: {}
  restartPolicy: Never
{{- end }}
 # jobs.yaml
{{- if .Values.master.jobs }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "jenkins.fullname" . }}-jobs
  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 }}"
data:
{{ toYaml .Values.master.jobs | indent 2 }}
{{- end -}}
 # rbac.yaml
{{ if .Values.rbac.create }}
{{- $serviceName := include "jenkins.fullname" . -}}

# This role is used to allow Jenkins scheduling of agents via Kubernetes plugin.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: {{ $serviceName }}-schedule-agents
  namespace: {{ template "jenkins.master.slaveKubernetesNamespace" . }}
  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 }}"
rules:
- apiGroups: [""]
  resources: ["pods", "pods/exec", "pods/log", "persistentvolumeclaims", "events"]
  verbs: ["get", "list", "watch"]
- apiGroups: [""]
  resources: ["pods", "pods/exec", "persistentvolumeclaims"]
  verbs: ["create", "delete", "deletecollection", "patch", "update"]

---

# We bind the role to the Jenkins service account. The role binding is created in the namespace
# where the agents are supposed to run.
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: {{ $serviceName }}-schedule-agents
  namespace: {{ template "jenkins.master.slaveKubernetesNamespace" . }}
  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 }}"
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: {{ $serviceName }}-schedule-agents
subjects:
- kind: ServiceAccount
  name: {{ template "jenkins.serviceAccountName" .}}
  namespace: {{ template "jenkins.namespace" . }}

---

{{- if .Values.rbac.readSecrets }}
# This is needed if you want to use https://jenkinsci.github.io/kubernetes-credentials-provider-plugin/
# as it needs permissions to get/watch/list Secrets
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: {{ template "jenkins.fullname" . }}-read-secrets
  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 }}"
rules:
  - apiGroups: [""]
    resources: ["secrets"]
    verbs: ["get", "watch", "list"]

---

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: {{ $serviceName }}-read-secrets
  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 }}"
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: {{ template "jenkins.fullname" . }}-read-secrets
subjects:
  - kind: ServiceAccount
    name: {{ template "jenkins.serviceAccountName" . }}
    namespace: {{ template "jenkins.namespace" . }}

---
{{- end}}

{{- if .Values.master.sidecars.configAutoReload.enabled }}
# The sidecar container which is responsible for reloading configuration changes
# needs permissions to watch ConfigMaps
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: {{ template "jenkins.fullname" . }}-casc-reload
  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 }}"
rules:
- apiGroups: [""]
  resources: ["configmaps"]
  verbs: ["get", "watch", "list"]

---

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: {{ $serviceName }}-watch-configmaps
  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 }}"
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: {{ template "jenkins.fullname" . }}-casc-reload
subjects:
- kind: ServiceAccount
  name: {{ template "jenkins.serviceAccountName" . }}
  namespace: {{ template "jenkins.namespace" . }}

{{- end}}

{{ end }}
 # secret-https-jks.yaml
{{- if and .Values.master.httpsKeyStore.enable ( not  .Values.master.httpsKeyStore.jenkinsHttpsJksSecretName ) -}}
apiVersion: v1
kind: Secret
metadata:
  name: {{ template "jenkins.fullname" . }}-https-jks
  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 }}"
type: Opaque
data:
  jenkins-jks-file: |
{{ .Values.master.httpsKeyStore.jenkinsKeyStoreBase64Encoded | indent 4 }}
  https-jks-password: {{ .Values.master.httpsKeyStore.password | b64enc }}
{{- end }}
 # secret.yaml
{{- if and (not .Values.master.admin.existingSecret) (.Values.master.useSecurity) -}}

apiVersion: v1
kind: Secret
metadata:
  name: {{ template "jenkins.fullname" . }}
  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 }}"
type: Opaque
data:
  {{ if .Values.master.adminPassword -}}
  jenkins-admin-password: {{ .Values.master.adminPassword | b64enc | quote }}
  {{ else -}}
  jenkins-admin-password: {{ randAlphaNum 10 | b64enc | quote }}
  {{ end -}}
  jenkins-admin-user: {{ .Values.master.adminUser | b64enc | quote }}
{{- end }}
 # service-account-agent.yaml
{{ if .Values.serviceAccountAgent.create }}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ include "jenkins.serviceAccountAgentName" . }}
  namespace: {{ template "jenkins.master.slaveKubernetesNamespace" . }}
{{- if .Values.serviceAccountAgent.annotations }}
  annotations:
{{ tpl (toYaml .Values.serviceAccountAgent.annotations) . | indent 4 }}
{{- end }}
  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 }}"
{{ end }}
 # service-account.yaml
{{ if .Values.serviceAccount.create }}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ include "jenkins.serviceAccountName" . }}
  namespace: {{ template "jenkins.namespace" . }}
{{- if .Values.serviceAccount.annotations }}
  annotations:
{{ tpl (toYaml .Values.serviceAccount.annotations) . | indent 4 }}
{{- end }}
  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 }}"
{{ end }}
 # test-config.yaml
{{- if .Values.master.testEnabled }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "jenkins.fullname" . }}-tests
  namespace: {{ template "jenkins.namespace" . }}
data:
  run.sh: |-
    @test "Testing Jenkins UI is accessible" {
      curl --retry 48 --retry-delay 10 {{ template "jenkins.fullname" . }}:{{ .Values.master.servicePort }}{{ default "" .Values.master.jenkinsUriPrefix }}/login
    }
{{- end }}

# Default values for jenkins.
# This is a YAML-formatted file.
# Declare name/value pairs to be passed into your templates.
# name: value

## Overrides for generated resource names
# See templates/_helpers.tpl
# nameOverride:
# fullnameOverride:
# namespaceOverride:

# For FQDN resolving of the master service. Change this value to match your existing configuration.
# ref: https://github.com/kubernetes/dns/blob/master/docs/specification.md
clusterZone: "cluster.local"

master:
  httpsKeyStore:
    jenkinsHttpsJksSecretName: ''
    enable: false
    httpPort: 8081
    path: "/var/jenkins_keystore"
    fileName: "keystore.jks"
    password: "password"
    # Convert keystore.jks files content to base64 ( cat keystore.jks | base64 ) and put the output here
    jenkinsKeyStoreBase64Encoded: |
        /u3+7QAAAAIAAAABAAAAAQANamVua2luc2NpLmNvbQAAAW2r/b1ZAAAFATCCBP0wDgYKKwYBBAEq
        AhEBAQUABIIE6QbCqasvoHS0pSwYqSvdydMCB9t+VNfwhFIiiuAelJfO5sSe2SebJbtwHgLcRz1Z
        gMtWgOSFdl3bWSzA7vrW2LED52h+jXLYSWvZzuDuh8hYO85m10ikF6QR+dTi4jra0whIFDvq3pxe
        TnESxEsN+DvbZM3jA3qsjQJSeISNpDjO099dqQvHpnCn18lyk7J4TWJ8sOQQb1EM2zDAfAOSqA/x
        QuPEFl74DlY+5DIk6EBvpmWhaMSvXzWZACGA0sYqa157dq7O0AqmuLG/EI5EkHETO4CrtBW+yLcy
        2dUCXOMA+j+NjM1BjrQkYE5vtSfNO6lFZcISyKo5pTFlcA7ut0Fx2nZ8GhHTn32CpeWwNcZBn1gR
        pZVt6DxVVkhTAkMLhR4rL2wGIi/1WRs23ZOLGKtyDNvDHnQyDiQEoJGy9nAthA8aNHa3cfdF10vB
        Drb19vtpFHmpvKEEhpk2EBRF4fTi644Fuhu2Ied6118AlaPvEea+n6G4vBz+8RWuVCmZjLU+7h8l
        Hy3/WdUPoIL5eW7Kz+hS+sRTFzfu9C48dMkQH3a6f3wSY+mufizNF9U298r98TnYy+PfDJK0bstG
        Ph6yPWx8DGXKQBwrhWJWXI6JwZDeC5Ny+l8p1SypTmAjpIaSW3ge+KgcL6Wtt1R5hUV1ajVwVSUi
        HF/FachKqPqyLJFZTGjNrxnmNYpt8P1d5JTvJfmfr55Su/P9n7kcyWp7zMcb2Q5nlXt4tWogOHLI
        OzEWKCacbFfVHE+PpdrcvCVZMDzFogIq5EqGTOZe2poPpBVE+1y9mf5+TXBegy5HToLWvmfmJNTO
        NCDuBjgLs2tdw2yMPm4YEr57PnMX5gGTC3f2ZihXCIJDCRCdQ9sVBOjIQbOCzxFXkVITo0BAZhCi
        Yz61wt3Ud8e//zhXWCkCsSV+IZCxxPzhEFd+RFVjW0Nm9hsb2FgAhkXCjsGROgoleYgaZJWvQaAg
        UyBzMmKDPKTllBHyE3Gy1ehBNGPgEBChf17/9M+j8pcm1OmlM434ctWQ4qW7RU56//yq1soFY0Te
        fu2ei03a6m68fYuW6s7XEEK58QisJWRAvEbpwu/eyqfs7PsQ+zSgJHyk2rO95IxdMtEESb2GRuoi
        Bs+AHNdYFTAi+GBWw9dvEgqQ0Mpv0//6bBE/Fb4d7b7f56uUNnnE7mFnjGmGQN+MvC62pfwfvJTT
        EkT1iZ9kjM9FprTFWXT4UmO3XTvesGeE50sV9YPm71X4DCQwc4KE8vyuwj0s6oMNAUACW2ClU9QQ
        y0tRpaF1tzs4N42Q5zl0TzWxbCCjAtC3u6xf+c8MCGrr7DzNhm42LOQiHTa4MwX4x96q7235oiAU
        iQqSI/hyF5yLpWw4etyUvsx2/0/0wkuTU1FozbLoCWJEWcPS7QadMrRRISxHf0YobIeQyz34regl
        t1qSQ3dCU9D6AHLgX6kqllx4X0fnFq7LtfN7fA2itW26v+kAT2QFZ3qZhINGfofCja/pITC1uNAZ
        gsJaTMcQ600krj/ynoxnjT+n1gmeqThac6/Mi3YlVeRtaxI2InL82ZuD+w/dfY9OpPssQjy3xiQa
        jPuaMWXRxz/sS9syOoGVH7XBwKrWpQcpchozWJt40QV5DslJkclcr8aC2AGlzuJMTdEgz1eqV0+H
        bAXG9HRHN/0eJTn1/QAAAAEABVguNTA5AAADjzCCA4swggJzAhRGqVxH4HTLYPGO4rzHcCPeGDKn
        xTANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCY2ExEDAOBgNVBAgMB29udGFyaW8xEDAOBgNV
        BAcMB3Rvcm9udG8xFDASBgNVBAoMC2plbmtpbnN0ZXN0MRkwFwYDVQQDDBBqZW5raW5zdGVzdC5p
        bmZvMR0wGwYJKoZIhvcNAQkBFg50ZXN0QHRlc3QuaW5mbzAeFw0xOTEwMDgxNTI5NTVaFw0xOTEx
        MDcxNTI5NTVaMIGBMQswCQYDVQQGEwJjYTEQMA4GA1UECAwHb250YXJpbzEQMA4GA1UEBwwHdG9y
        b250bzEUMBIGA1UECgwLamVua2luc3Rlc3QxGTAXBgNVBAMMEGplbmtpbnN0ZXN0LmluZm8xHTAb
        BgkqhkiG9w0BCQEWDnRlc3RAdGVzdC5pbmZvMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
        AQEA02q352JTHGvROMBhSHvSv+vnoOTDKSTz2aLQn0tYrIRqRo+8bfmMjXuhkwZPSnCpvUGNAJ+w
        Jrt/dqMoYUjCBkjylD/qHmnXN5EwS1cMg1Djh65gi5JJLFJ7eNcoSsr/0AJ+TweIal1jJSP3t3PF
        9Uv21gm6xdm7HnNK66WpUUXLDTKaIs/jtagVY1bLOo9oEVeLN4nT2CYWztpMvdCyEDUzgEdDbmrP
        F5nKUPK5hrFqo1Dc5rUI4ZshL3Lpv398aMxv6n2adQvuL++URMEbXXBhxOrT6rCtYzbcR5fkwS9i
        d3Br45CoWOQro02JAepoU0MQKY5+xQ4Bq9Q7tB9BAwIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQAe
        4xc+mSvKkrKBHg9/zpkWgZUiOp4ENJCi8H4tea/PCM439v6y/kfjT/okOokFvX8N5aa1OSz2Vsrl
        m8kjIc6hiA7bKzT6lb0EyjUShFFZ5jmGVP4S7/hviDvgB5yEQxOPpumkdRP513YnEGj/o9Pazi5h
        /MwpRxxazoda9r45kqQpyG+XoM4pB+Fd3JzMc4FUGxfVPxJU4jLawnJJiZ3vqiSyaB0YyUL+Er1Q
        6NnqtR4gEBF0ZVlQmkycFvD4EC2boP943dLqNUvop+4R3SM1QMM6P5u8iTXtHd/VN4MwMyy1wtog
        hYAzODo1Jt59pcqqKJEas0C/lFJEB3frw4ImNx5fNlJYOpx+ijfQs9m39CevDq0=
  # Used for label app.kubernetes.io/component
  componentName: "jenkins-master"
  image: "jenkins/jenkins"
  tag: "lts"
  imagePullPolicy: "Always"
  imagePullSecretName:
  # Optionally configure lifetime for master-container
  lifecycle:
  #  postStart:
  #    exec:
  #      command:
  #      - "uname"
  #      - "-a"
  disableRememberMe: false
  numExecutors: 0
  # configures the executor mode of the Jenkins node. Possible values are: NORMAL or EXCLUSIVE
  executorMode: "NORMAL"
  # This is ignored if enableRawHtmlMarkupFormatter is true
  markupFormatter: plainText
  customJenkinsLabels: []
  # configAutoReload requires UseSecurity is set to true:
  useSecurity: true

  # enables configuration done directly via XML files
  enableXmlConfig: false
  # Allows to configure different SecurityRealm using Jenkins XML
  securityRealm: |-
    <securityRealm class="hudson.security.LegacySecurityRealm"/>
  # Allows to configure different AuthorizationStrategy using Jenkins XML
  authorizationStrategy: |-
     <authorizationStrategy class="hudson.security.FullControlOnceLoggedInAuthorizationStrategy">
       <denyAnonymousReadAccess>true</denyAnonymousReadAccess>
     </authorizationStrategy>
  hostNetworking: false
  # When enabling LDAP or another non-Jenkins identity source, the built-in admin account will no longer exist.
  # If you disable the non-Jenkins identity store and instead use the Jenkins internal one,
  # you should revert master.adminUser to your preferred admin user:
  adminUser: "admin"
  # adminPassword: <defaults to random>
  admin:
    existingSecret: ""
    userKey: jenkins-admin-user
    passwordKey: jenkins-admin-password
  # This values should not be changed unless you use your custom image of jenkins or any devired from. If you want to use
  # Cloudbees Jenkins Distribution docker, you should set jenkinsHome: "/var/cloudbees-jenkins-distribution"
  jenkinsHome: "/var/jenkins_home"
  # This values should not be changed unless you use your custom image of jenkins or any devired from. If you want to use
  # Cloudbees Jenkins Distribution docker, you should set jenkinsRef: "/usr/share/cloudbees-jenkins-distribution/ref"
  jenkinsRef: "/usr/share/jenkins/ref"
  rollingUpdate: {}
  # Ignored if Persistence is enabled
  # maxSurge: 1
  # maxUnavailable: 25%
  resources:
    requests:
      cpu: "50m"
      memory: "256Mi"
    limits:
      cpu: "2000m"
      memory: "4096Mi"
  # Environment variables that get added to the init container (useful for e.g. http_proxy)
  # initContainerEnv:
  #   - name: http_proxy
  #     value: "http://192.168.64.1:3128"
  # containerEnv:
  #   - name: http_proxy
  #     value: "http://192.168.64.1:3128"
  # Set min/max heap here if needed with:
  # javaOpts: "-Xms512m -Xmx512m"
  # jenkinsOpts: ""
  # jenkinsUrl: ""
  # If you set this prefix and use ingress controller then you might want to set the ingress path below
  # jenkinsUriPrefix: "/jenkins"
  # Enable pod security context (must be `true` if runAsUser or fsGroup are set)
  usePodSecurityContext: true
  # Set runAsUser to 1000 to let Jenkins run as non-root user 'jenkins' which exists in 'jenkins/jenkins' docker image.
  # When setting runAsUser to a different value than 0 also set fsGroup to the same value:
  runAsUser: 1000
  fsGroup: 1000
  servicePort: 8080
  targetPort: 8080
  # For minikube, set this to NodePort, elsewhere use LoadBalancer
  # Use ClusterIP if your setup includes ingress controller
  serviceType: ClusterIP
  # Jenkins master service annotations
  serviceAnnotations: {}
  # Jenkins master custom labels
  deploymentLabels: {}
  #   foo: bar
  #   bar: foo
  # Jenkins master service labels
  serviceLabels: {}
  #   service.beta.kubernetes.io/aws-load-balancer-backend-protocol: https
  # Put labels on Jenkins master pod
  podLabels: {}
  # Used to create Ingress record (should used with ServiceType: ClusterIP)
  # nodePort: <to set explicitly, choose port between 30000-32767
  # Enable Kubernetes Liveness and Readiness Probes
  # ~ 2 minutes to allow Jenkins to restart when upgrading plugins. Set ReadinessTimeout to be shorter than LivenessTimeout.
  healthProbes: true
  healthProbesLivenessTimeout: 5
  healthProbesReadinessTimeout: 5
  healthProbeLivenessPeriodSeconds: 10
  healthProbeReadinessPeriodSeconds: 10
  healthProbeLivenessFailureThreshold: 5
  healthProbeReadinessFailureThreshold: 3
  healthProbeLivenessInitialDelay: 90
  healthProbeReadinessInitialDelay: 60
  slaveListenerPort: 50000
  slaveHostPort:
  disabledAgentProtocols:
    - JNLP-connect
    - JNLP2-connect
  csrf:
    defaultCrumbIssuer:
      enabled: true
      proxyCompatability: true
  cli: false
  # Kubernetes service type for the JNLP agent service
  # slaveListenerServiceType is the Kubernetes Service type for the JNLP agent service,
  # either 'LoadBalancer', 'NodePort', or 'ClusterIP'
  # Note if you set this to 'LoadBalancer', you *must* define annotations to secure it. By default
  # this will be an external load balancer and allowing inbound 0.0.0.0/0, a HUGE
  # security risk:  https://github.com/kubernetes/charts/issues/1341
  slaveListenerServiceType: "ClusterIP"
  # Optionally assign an IP to the LoadBalancer slaveListenerService LoadBalancer
  # GKE users: only regional static IPs will work for Service Load balancer.
  # slaveListenerLoadBalancerIP: 1.2.3.4
  slaveListenerServiceAnnotations: {}
  slaveDefaultsProviderTemplate: ""
  slaveConnectTimeout: 5
  slaveReadTimeout: 15
  slaveKubernetesNamespace:
  slaveJenkinsUrl:
  slaveJenkinsTunnel:

  # Example of 'LoadBalancer' type of agent listener with annotations securing it
  # slaveListenerServiceType: LoadBalancer
  # slaveListenerServiceAnnotations:
  #   service.beta.kubernetes.io/aws-load-balancer-internal: "True"
  #   service.beta.kubernetes.io/load-balancer-source-ranges: "172.0.0.0/8, 10.0.0.0/8"

  # LoadBalancerSourcesRange is a list of allowed CIDR values, which are combined with ServicePort to
  # set allowed inbound rules on the security group assigned to the master load balancer
  loadBalancerSourceRanges:
  - 0.0.0.0/0
  # Optionally assign a known public LB IP
  # loadBalancerIP: 1.2.3.4
  # Optionally configure a JMX port
  # requires additional javaOpts, ie
  # javaOpts: >
  #   -Dcom.sun.management.jmxremote.port=4000
  #   -Dcom.sun.management.jmxremote.authenticate=false
  #   -Dcom.sun.management.jmxremote.ssl=false
  # jmxPort: 4000
  # Optionally configure other ports to expose in the master container
  extraPorts: []
  # - name: BuildInfoProxy
  #   port: 9000

  # List of plugins to be install during Jenkins master start
  installPlugins:
    - kubernetes:1.25.7
    - workflow-job:2.39
    - workflow-aggregator:2.6
    - credentials-binding:1.23
    - git:4.2.2
    - configuration-as-code:1.41

  # List of plugins to install in addition to those listed in master.installPlugins
  additionalPlugins: []

  # Enable to initialize the Jenkins master only once on initial installation.
  # Without this, whenever the master gets restarted (Evicted, etc.) it will fetch plugin updates which has the potential to cause breakage.
  # Note that for this to work, `persistence.enabled` needs to be set to `true`
  initializeOnce: false

  # Enable to always override the installed plugins with the values of 'master.installPlugins' on upgrade or redeployment.
  # overwritePlugins: true

  # Configures if plugins bundled with `master.image` should be overwritten with the values of 'master.installPlugins' on upgrade or redeployment.
  overwritePluginsFromImage: true

  # Enable HTML parsing using OWASP Markup Formatter Plugin (antisamy-markup-formatter), useful with ghprb plugin.
  # The plugin is not installed by default, please update master.installPlugins.
  enableRawHtmlMarkupFormatter: false
  # Used to approve a list of groovy functions in pipelines used the script-security plugin. Can be viewed under /scriptApproval
  scriptApproval: []
  #  - "method groovy.json.JsonSlurperClassic parseText java.lang.String"
  #  - "new groovy.json.JsonSlurperClassic"
  # List of groovy init scripts to be executed during Jenkins master start
  initScripts: []
  #  - |
  #    print 'adding global pipeline libraries, register properties, bootstrap jobs...'
  # Kubernetes secret that contains a 'credentials.xml' for Jenkins
  # credentialsXmlSecret: jenkins-credentials
  # Kubernetes secret that contains files to be put in the Jenkins 'secrets' directory,
  # useful to manage encryption keys used for credentials.xml for instance (such as
  # master.key and hudson.util.Secret)
  # secretsFilesSecret: jenkins-secrets
  # Jenkins XML job configs to provision
  jobs: {}
  #  test: |-
  #    <<xml here>>

  # Below is the implementation of Jenkins Configuration as Code.  Add a key under configScripts for each configuration area,
  # where each corresponds to a plugin or section of the UI.  Each key (prior to | character) is just a label, and can be any value.
  # Keys are only used to give the section a meaningful name.  The only restriction is they may only contain RFC 1123 \ DNS label
  # characters: lowercase letters, numbers, and hyphens.  The keys become the name of a configuration yaml file on the master in
  # /var/jenkins_home/casc_configs (by default) and will be processed by the Configuration as Code Plugin.  The lines after each |
  # become the content of the configuration yaml file.  The first line after this is a JCasC root element, eg jenkins, credentials,
  # etc.  Best reference is https://<jenkins_url>/configuration-as-code/reference.  The example below creates a welcome message:
  JCasC:
    enabled: true
    defaultConfig: true
    configScripts: {}
    # Ignored if securityRealm is defined in master.JCasC.configScripts and
    # ignored if master.enableXmlConfig=true as master.securityRealm takes precedence
    securityRealm: |-
      legacy
    # Ignored if authorizationStrategy is defined in master.JCasC.configScripts and
    # ignored if master.enableXmlConfig=true as master.authorizationStrategy takes precedence
    authorizationStrategy: |-
      loggedInUsersCanDoAnything:
        allowAnonymousRead: false
    # welcome-message: |
    #   jenkins:
    #     systemMessage: Welcome to our CI\CD server.  This Jenkins is configured and managed 'as code'.
  # Optionally specify additional init-containers
  customInitContainers: []
  # - name: custom-init
  #   image: "alpine:3.7"
  #   imagePullPolicy: Always
  #   command: [ "uname", "-a" ]

  sidecars:
    configAutoReload:
      # If enabled: true, Jenkins Configuration as Code will be reloaded on-the-fly without a reboot.  If false or not-specified,
      # jcasc changes will cause a reboot and will only be applied at the subsequent start-up.  Auto-reload uses the
      # http://<jenkins_url>/reload-configuration-as-code endpoint to reapply config when changes to the configScripts are detected.
      enabled: true
      image: kiwigrid/k8s-sidecar:0.1.144
      imagePullPolicy: IfNotPresent
      resources: {}
        #   limits:
        #     cpu: 100m
        #     memory: 100Mi
        #   requests:
        #     cpu: 50m
        #     memory: 50Mi
      # How many connection-related errors to retry on
      reqRetryConnect: 10
      # env:
      #   - name: REQ_TIMEOUT
      #     value: "30"
      # SSH port value can be set to any unused TCP port.  The default, 1044, is a non-standard SSH port that has been chosen at random.
      # Is only used to reload jcasc config from the sidecar container running in the Jenkins master pod.
      # This TCP port will not be open in the pod (unless you specifically configure this), so Jenkins will not be
      # accessible via SSH from outside of the pod.  Note if you use non-root pod privileges (runAsUser & fsGroup),
      # this must be > 1024:
      sshTcpPort: 1044
      # folder in the pod that should hold the collected dashboards:
      folder: "/var/jenkins_home/casc_configs"
      # If specified, the sidecar will search for JCasC config-maps inside this namespace.
      # Otherwise the namespace in which the sidecar is running will be used.
      # It's also possible to specify ALL to search in all namespaces:
      # searchNamespace:

    # Allows you to inject additional/other sidecars
    other: []
    ## The example below runs the client for https://smee.io as sidecar container next to Jenkins,
    ## that allows to trigger build behind a secure firewall.
    ## https://jenkins.io/blog/2019/01/07/webhook-firewalls/#triggering-builds-with-webhooks-behind-a-secure-firewall
    ##
    ## Note: To use it you should go to https://smee.io/new and update the url to the generete one.
    # - name: smee
    #   image: docker.io/twalter/smee-client:1.0.2
    #   args: ["--port", "{{ .Values.master.servicePort }}", "--path", "/github-webhook/", "--url", "https://smee.io/new"]
    #   resources:
    #     limits:
    #       cpu: 50m
    #       memory: 128Mi
    #     requests:
    #       cpu: 10m
    #       memory: 32Mi
  # Node labels and tolerations for pod assignment
  # ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#nodeselector
  # ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#taints-and-tolerations-beta-feature
  nodeSelector: {}

  terminationGracePeriodSeconds:

  tolerations: []
  # Leverage a priorityClass to ensure your pods survive resource shortages
  # ref: https://kubernetes.io/docs/concepts/configuration/pod-priority-preemption/
  # priorityClass: system-cluster-critical
  podAnnotations: {}
  # Add deployment annotation
  deploymentAnnotations: {}

  # The below two configuration-related values are deprecated and replaced by Jenkins Configuration as Code (see above
  # JCasC key).  They will be deleted in an upcoming version.
  customConfigMap: false
  # By default, the configMap is only used to set the initial config the first time
  # that the chart is installed.  Setting `overwriteConfig` to `true` will overwrite
  # the jenkins config with the contents of the configMap every time the pod starts.
  # This will also overwrite all init scripts
  overwriteConfig: false

  # By default, the Jobs Map is only used to set the initial jobs the first time
  # that the chart is installed.  Setting `overwriteJobs` to `true` will overwrite
  # the jenkins jobs configuration with the contents of Jobs every time the pod starts.
  overwriteJobs: false

  ingress:
    enabled: false
    # Override for the default paths that map requests to the backend
    paths: []
    # - backend:
    #     serviceName: ssl-redirect
    #     servicePort: use-annotation
    # - backend:
    #     serviceName: >-
    #       {{ template "jenkins.fullname" . }}
    #     # Don't use string here, use only integer value!
    #     servicePort: 8080
    # For Kubernetes v1.14+, use 'networking.k8s.io/v1beta1'
    apiVersion: "extensions/v1beta1"
    labels: {}
    annotations: {}
    # kubernetes.io/ingress.class: nginx
    # kubernetes.io/tls-acme: "true"
    # Set this path to jenkinsUriPrefix above or use annotations to rewrite path
    # path: "/jenkins"
    # configures the hostname e.g. jenkins.example.com
    hostName:
    tls:
    # - secretName: jenkins.cluster.local
    #   hosts:
    #     - jenkins.cluster.local

  # If you're running on GKE and need to configure a backendconfig
  # to finish ingress setup, use the following values.
  # Docs: https://cloud.google.com/kubernetes-engine/docs/concepts/backendconfig
  backendconfig:
    enabled: false
    apiVersion: "extensions/v1beta1"
    name:
    labels: {}
    annotations: {}
    spec: {}

  # Openshift route
  route:
    enabled: false
    labels: {}
    annotations: {}
    # path: "/jenkins"

  additionalConfig: {}

  # master.hostAliases allows for adding entries to Pod /etc/hosts:
  # https://kubernetes.io/docs/concepts/services-networking/add-entries-to-pod-etc-hosts-with-host-aliases/
  hostAliases: []
  # - ip: 192.168.50.50
  #   hostnames:
  #     - something.local
  # - ip: 10.0.50.50
  #   hostnames:
  #     - other.local

  # Expose Prometheus metrics
  prometheus:
    # If enabled, add the prometheus plugin to the list of plugins to install
    # https://plugins.jenkins.io/prometheus
    enabled: false
    # Additional labels to add to the ServiceMonitor object
    serviceMonitorAdditionalLabels: {}
    # Set a custom namespace where to deploy ServiceMonitor resource
    # serviceMonitorNamespace: monitoring
    scrapeInterval: 60s
    # This is the default endpoint used by the prometheus plugin
    scrapeEndpoint: /prometheus
    # Additional labels to add to the PrometheusRule object
    alertingRulesAdditionalLabels: {}
    # An array of prometheus alerting rules
    # See here: https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/
    # The `groups` root object is added by default, simply add the rule entries
    alertingrules: []

  # Can be used to disable rendering master test resources when using helm template
  testEnabled: true

agent:
  enabled: true
  image: "jenkins/inbound-agent"
  tag: "4.3-4"
  workingDir: "/home/jenkins"
  customJenkinsLabels: []
  # name of the secret to be used for image pulling
  imagePullSecretName:
  componentName: "jenkins-slave"
  privileged: false
  runAsUser:
  runAsGroup:
  resources:
    requests:
      cpu: "512m"
      memory: "512Mi"
    limits:
      cpu: "512m"
      memory: "512Mi"
  # You may want to change this to true while testing a new image
  alwaysPullImage: false
  # Controls how agent pods are retained after the Jenkins build completes
  # Possible values: Always, Never, OnFailure
  podRetention: "Never"
  # You can define the volumes that you want to mount for this container
  # Allowed types are: ConfigMap, EmptyDir, HostPath, Nfs, PVC, Secret
  # Configure the attributes as they appear in the corresponding Java class for that type
  # https://github.com/jenkinsci/kubernetes-plugin/tree/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/volumes
  volumes: []
  # - type: ConfigMap
  #   configMapName: myconfigmap
  #   mountPath: /var/myapp/myconfigmap
  # - type: EmptyDir
  #   mountPath: /var/myapp/myemptydir
  #   memory: false
  # - type: HostPath
  #   hostPath: /var/lib/containers
  #   mountPath: /var/myapp/myhostpath
  # - type: Nfs
  #   mountPath: /var/myapp/mynfs
  #   readOnly: false
  #   serverAddress: "192.0.2.0"
  #   serverPath: /var/lib/containers
  # - type: PVC
  #   claimName: mypvc
  #   mountPath: /var/myapp/mypvc
  #   readOnly: false
  # - type: Secret
  #   defaultMode: "600"
  #   mountPath: /var/myapp/mysecret
  #   secretName: mysecret
  # Pod-wide ennvironment, these vars are visible to any container in the agent pod
  envVars: []
  # - name: PATH
  #   value: /usr/local/bin
  nodeSelector: {}
  # Key Value selectors. Ex:
  # jenkins-agent: v1

  # Executed command when side container gets started
  command:
  args: "${computer.jnlpmac} ${computer.name}"
  # Side container name
  sideContainerName: "jnlp"
  # Doesn't allocate pseudo TTY by default
  TTYEnabled: false
  # Max number of spawned agent
  containerCap: 10
  # Pod name
  podName: "default"
  # Allows the Pod to remain active for reuse until the configured number of
  # minutes has passed since the last step was executed on it.
  idleMinutes: 0
  # Raw yaml template for the Pod. For example this allows usage of toleration for agent pods.
  # https://github.com/jenkinsci/kubernetes-plugin#using-yaml-to-define-pod-templates
  # https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/
  yamlTemplate: ""
  # yamlTemplate: |-
  #   apiVersion: v1
  #   kind: Pod
  #   spec:
  #     tolerations:
  #     - key: "key"
  #       operator: "Equal"
  #       value: "value"
  # Defines how the raw yaml field gets merged with yaml definitions from inherited pod templates: merge or override
  yamlMergeStrategy: "override"
  # Timeout in seconds for an agent to be online
  slaveConnectTimeout: 100

  # Below is the implementation of custom pod templates for the default configured kubernetes cloud.
  # Add a key under podTemplates for each pod template. Each key (prior to | character) is just a label, and can be any value.
  # Keys are only used to give the pod template a meaningful name.  The only restriction is they may only contain RFC 1123 \ DNS label
  # characters: lowercase letters, numbers, and hyphens. Each pod template can contain multiple containers.
  # For this pod templates configuration to be loaded the following values must be set:
  # master.JCasC.enabled: true
  # master.JCasC.defaultConfig: true
  # Best reference is https://<jenkins_url>/configuration-as-code/reference#Cloud-kubernetes. The example below creates a python pod template.
  podTemplates: {}
  #  python: |
  #    - name: python
  #      label: jenkins-python
  #      serviceAccount: jenkins
  #      containers:
  #        - name: python
  #          image: python:3
  #          command: "/bin/sh -c"
  #          args: "cat"
  #          ttyEnabled: true
  #          privileged: true
  #          resourceRequestCpu: "400m"
  #          resourceRequestMemory: "512Mi"
  #          resourceLimitCpu: "1"
  #          resourceLimitMemory: "1024Mi"

# Here you can add additional agents
# They inherit all values from `agent` so you only need to specify values which differ
additionalAgents: {}
#  maven:
#    podName: maven
#    customJenkinsLabels: maven
#    # An example of overriding the jnlp container
#    # sideContainerName: jnlp
#    image: jenkins/jnlp-agent-maven
#    tag: latest
#  python:
#    podName: python
#    customJenkinsLabels: python
#    sideContainerName: python
#    image: python
#    tag: "3"
#    command: "/bin/sh -c"
#    args: "cat"
#    TTYEnabled: true

persistence:
  enabled: true
  ## A manually managed Persistent Volume and Claim
  ## Requires persistence.enabled: true
  ## If defined, PVC must be created manually before volume will be bound
  existingClaim:
  ## jenkins data Persistent Volume Storage Class
  ## If defined, storageClassName: <storageClass>
  ## If set to "-", storageClassName: "", which disables dynamic provisioning
  ## If undefined (the default) or set to null, no storageClassName spec is
  ##   set, choosing the default provisioner.  (gp2 on AWS, standard on
  ##   GKE, AWS & OpenStack)
  ##
  storageClass:
  annotations: {}
  accessMode: "ReadWriteOnce"
  size: "8Gi"
  volumes:
  #  - name: nothing
  #    emptyDir: {}
  mounts:
  #  - mountPath: /var/nothing
  #    name: nothing
  #    readOnly: true

networkPolicy:
  # Enable creation of NetworkPolicy resources.
  enabled: false
  # For Kubernetes v1.4, v1.5 and v1.6, use 'extensions/v1beta1'
  # For Kubernetes v1.7, use 'networking.k8s.io/v1'
  apiVersion: networking.k8s.io/v1
  # You can allow agents to connect from both within the cluster (from within specific/all namespaces) AND/OR from a given external IP range
  internalAgents:
    allowed: true
    podLabels: {}
    namespaceLabels: {}
      # project: myproject
  externalAgents: {}
  #   ipCIDR: 172.17.0.0/16
  #   except:
  #     - 172.17.1.0/24

## Install Default RBAC roles and bindings
rbac:
  create: true
  readSecrets: false

serviceAccount:
  create: true
  # The name of the service account is autogenerated by default
  name:
  annotations: {}

serviceAccountAgent:
  # Specifies whether a ServiceAccount should be created
  create: false
  # The name of the ServiceAccount to use.
  # If not set and create is true, a name is generated using the fullname template
  name:
  annotations: {}

## Backup cronjob configuration
## Ref: https://github.com/maorfr/kube-tasks
backup:
  # Backup must use RBAC
  # So by enabling backup you are enabling RBAC specific for backup
  enabled: false
  # Used for label app.kubernetes.io/component
  componentName: "backup"
  # Schedule to run jobs. Must be in cron time format
  # Ref: https://crontab.guru/
  schedule: "0 2 * * *"
  labels: {}
  annotations: {}
    # Example for authorization to AWS S3 using kube2iam
    # Can also be done using environment variables
    # iam.amazonaws.com/role: "jenkins"
  image:
    repository: "maorfr/kube-tasks"
    tag: "0.2.0"
  # Additional arguments for kube-tasks
  # Ref: https://github.com/maorfr/kube-tasks#simple-backup
  extraArgs: []
  # Add existingSecret for AWS credentials
  existingSecret: {}
  ## Example for using an existing secret
   # jenkinsaws:
  ## Use this key for AWS access key ID
     # awsaccesskey: jenkins_aws_access_key
  ## Use this key for AWS secret access key
     # awssecretkey: jenkins_aws_secret_key
  # Add additional environment variables
   # jenkinsgcp:
  ## Use this key for GCP credentials
     # gcpcredentials: credentials.json
  env: []
  # Example environment variable required for AWS credentials chain
  # - name: "AWS_REGION"
  #   value: "us-east-1"
  resources:
    requests:
      memory: 1Gi
      cpu: 1
    limits:
      memory: 1Gi
      cpu: 1
  # Destination to store the backup artifacts
  # Supported cloud storage services: AWS S3, Minio S3, Azure Blob Storage, Google Cloud Storage
  # Additional support can added. Visit this repository for details
  # Ref: https://github.com/maorfr/skbn
  destination: "s3://jenkins-data/backup"
checkDeprecation: true
