# _helpers.tpl
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "cert-manager.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
{{- 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).
*/}}
{{- define "cert-manager.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 -}}

{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "cert-manager.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
Create the name of the service account to use
*/}}
{{- define "cert-manager.serviceAccountName" -}}
{{- if .Values.serviceAccount.create -}}
    {{ default (include "cert-manager.fullname" .) .Values.serviceAccount.name }}
{{- else -}}
    {{ default "default" .Values.serviceAccount.name }}
{{- end -}}
{{- end -}}
 # apiservice.yaml
apiVersion: apiregistration.k8s.io/v1beta1
kind: APIService
metadata:
  name: v1beta1.admission.certmanager.k8s.io
  labels:
    app: {{ include "webhook.name" . }}
    chart: {{ include "webhook.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
spec:
  group: admission.certmanager.k8s.io
  groupPriorityMinimum: 1000
  versionPriority: 15
  service:
    name: {{ include "webhook.fullname" . }}
    namespace: "{{ .Release.Namespace }}"
  version: v1beta1
 # ca-sync.yaml
## This file contains a CronJob that runs every week to automatically update the
## caBundle set on the APIService and ValidatingWebhookConfiguration resource.
## This allows us to store the CA bundle in a Secret resource which is
## generated by cert-manager's 'selfsigned' Issuer.
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: {{ include "webhook.fullname" . }}-ca-sync
  namespace: {{ .Release.Namespace | quote }}
  labels:
    app: {{ include "webhook.name" . }}
    chart: {{ include "webhook.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
spec:
  schedule: "@weekly"
  jobTemplate:
    spec:
      backoffLimit: 20
      template:
        metadata:
          labels:
            app: ca-helper
        spec:
          serviceAccountName: {{ include "webhook.fullname" . }}-ca-sync
          restartPolicy: OnFailure
          containers:
          - name: ca-helper
            image: {{ .Values.caSyncImage.repository }}:{{ .Values.caSyncImage.tag }}
            imagePullPolicy: {{ .Values.caSyncImage.pullPolicy }}
            args:
            - -config=/config/config
            volumeMounts:
            - name: config
              mountPath: /config
            resources:
              requests:
                cpu: 10m
                memory: 32Mi
              limits:
                cpu: 100m
                memory: 128Mi
          volumes:
          - name: config
            configMap:
              name: {{ include "webhook.fullname" . }}-ca-sync
---
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ include "webhook.fullname" . }}-ca-sync
  namespace: {{ .Release.Namespace | quote }}
  labels:
    app: {{ include "webhook.name" . }}
    chart: {{ include "webhook.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
spec:
  backoffLimit: 20
  template:
    metadata:
      labels:
        app: ca-helper
    spec:
      serviceAccountName: {{ include "webhook.fullname" . }}-ca-sync
      restartPolicy: OnFailure
      containers:
      - name: ca-helper
        image: {{ .Values.caSyncImage.repository }}:{{ .Values.caSyncImage.tag }}
        imagePullPolicy: {{ .Values.caSyncImage.pullPolicy }}
        args:
        - -config=/config/config
        volumeMounts:
        - name: config
          mountPath: /config
        resources:
          requests:
            cpu: 10m
            memory: 32Mi
          limits:
            cpu: 100m
            memory: 128Mi
      volumes:
      - name: config
        configMap:
          name: {{ include "webhook.fullname" . }}-ca-sync
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "webhook.fullname" . }}-ca-sync
  namespace: {{ .Release.Namespace | quote }}
  labels:
    app: {{ include "webhook.name" . }}
    chart: {{ include "webhook.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
data:
  config: |-
    {
        "apiServices": [
            {
                "name": "v1beta1.admission.certmanager.k8s.io",
                "secret": {
                    "name": "{{ include "webhook.rootCACertificate" . }}",
                    "namespace": "{{ .Release.Namespace }}",
                    "key": "tls.crt"
                }
            }
        ],
        "validatingWebhookConfigurations": [
            {
                "name": "{{ include "webhook.fullname" . }}",
                "file": {
                    "path": "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"
                }
            }
        ]
    }
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ include "webhook.fullname" . }}-ca-sync
  namespace: {{ .Release.Namespace | quote }}
  labels:
    app: {{ include "webhook.name" . }}
    chart: {{ include "webhook.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRole
metadata:
  name: {{ include "webhook.fullname" . }}-ca-sync
  labels:
    app: {{ include "webhook.name" . }}
    chart: {{ include "webhook.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
rules:
  - apiGroups: [""]
    resources: ["secrets"]
    verbs: ["get"]
    resourceNames:
    - {{ include "webhook.rootCACertificate" . }}
  - apiGroups: ["admissionregistration.k8s.io"]
    resources: ["validatingwebhookconfigurations", "mutatingwebhookconfigurations"]
    verbs: ["get", "update"]
    resourceNames:
    - {{ include "webhook.fullname" . }}
  - apiGroups: ["apiregistration.k8s.io"]
    resources: ["apiservices"]
    verbs: ["get", "update"]
    resourceNames:
    - v1beta1.admission.certmanager.k8s.io
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: {{ include "webhook.fullname" . }}-ca-sync
  labels:
    app: {{ include "webhook.name" . }}
    chart: {{ include "webhook.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: {{ include "webhook.fullname" . }}-ca-sync
subjects:
  - name: {{ include "webhook.fullname" . }}-ca-sync
    namespace: {{ .Release.Namespace }}
    kind: ServiceAccount
 # deployment.yaml
apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: {{ template "cert-manager.fullname" . }}
  namespace: {{ .Release.Namespace | quote }}
  labels:
    app: {{ template "cert-manager.name" . }}
    chart: {{ template "cert-manager.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      app: {{ template "cert-manager.name" . }}
      release: {{ .Release.Name }}
  {{- with .Values.strategy }}
  strategy:
    {{- . | toYaml | nindent 4 }}
  {{- end }}
  template:
    metadata:
      labels:
        app: {{ template "cert-manager.name" . }}
        release: {{ .Release.Name }}
{{- if .Values.podLabels }}
{{ toYaml .Values.podLabels | indent 8 }}
{{- end }}
      annotations:
      {{- if .Values.podAnnotations }}
{{ toYaml .Values.podAnnotations | indent 8 }}
      {{- end }}
    spec:
      serviceAccountName: {{ template "cert-manager.serviceAccountName" . }}
      {{- if .Values.global.priorityClassName }}
      priorityClassName: {{ .Values.global.priorityClassName | quote }}
      {{- end }}
      {{- if .Values.securityContext.enabled }}
      securityContext:
        fsGroup: {{ .Values.securityContext.fsGroup }}
        runAsUser: {{ .Values.securityContext.runAsUser }}
      {{- end }}
      containers:
        - name: {{ .Chart.Name }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          args:
        {{- if .Values.clusterResourceNamespace }}
          - --cluster-resource-namespace={{ .Values.clusterResourceNamespace }}
        {{- else }}
          - --cluster-resource-namespace=$(POD_NAMESPACE)
        {{- end }}
        {{- if .Values.leaderElection.namespace }}
          - --leader-election-namespace={{ .Values.leaderElection.namespace }}
        {{- else }}
          - --leader-election-namespace=$(POD_NAMESPACE)
        {{- end }}
        {{- if .Values.extraArgs }}
{{ toYaml .Values.extraArgs | indent 10 }}
        {{- end }}
          {{- with .Values.ingressShim }}
          {{- if .defaultIssuerName }}
          - --default-issuer-name={{ .defaultIssuerName }}
          {{- end }}
          {{- if .defaultIssuerKind }}
          - --default-issuer-kind={{ .defaultIssuerKind }}
          {{- end }}
          {{- if .defaultACMEChallengeType }}
          - --default-acme-issuer-challenge-type={{ .defaultACMEChallengeType }}
          {{- end }}
          {{- if .defaultACMEDNS01ChallengeProvider }}
          - --default-acme-issuer-dns01-provider-name={{ .defaultACMEDNS01ChallengeProvider }}
          {{- end }}
          {{- end }}
          env:
          - name: POD_NAMESPACE
            valueFrom:
              fieldRef:
                fieldPath: metadata.namespace
        {{- if .Values.extraEnv }}
{{ toYaml .Values.extraEnv | indent 10 }}
        {{- end }}
          {{- if .Values.http_proxy }}
          - name: HTTP_PROXY
            value: {{ .Values.http_proxy }}
          {{- end }}
          {{- if .Values.https_proxy }}
          - name: HTTPS_PROXY
            value: {{ .Values.https_proxy }}
          {{- end }}
          {{- if .Values.no_proxy }}
          - name: NO_PROXY
            value: {{ .Values.no_proxy }}
          {{- end }}
          resources:
{{ toYaml .Values.resources | indent 12 }}
    {{- with .Values.nodeSelector }}
      nodeSelector:
{{ toYaml . | indent 8 }}
    {{- end }}
    {{- with .Values.affinity }}
      affinity:
{{ toYaml . | indent 8 }}
    {{- end }}
    {{- with .Values.tolerations }}
      tolerations:
{{ toYaml . | indent 8 }}
    {{- end }}
{{- if .Values.podDnsPolicy }}
      dnsPolicy: {{ .Values.podDnsPolicy }}
{{- end }}
{{- if .Values.podDnsConfig }}
      dnsConfig:
{{ toYaml .Values.podDnsConfig | indent 8 }}
{{- end }}
 # pki.yaml
---
# Create a selfsigned Issuer, in order to create a root CA certificate for
# signing webhook serving certificates
apiVersion: certmanager.k8s.io/v1alpha1
kind: Issuer
metadata:
  name: {{ include "webhook.selfSignedIssuer" . }}
  namespace: {{ .Release.Namespace | quote }}
  labels:
    app: {{ include "webhook.name" . }}
    chart: {{ include "webhook.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
spec:
  selfSigned: {}

---

# Generate a CA Certificate used to sign certificates for the webhook
apiVersion: certmanager.k8s.io/v1alpha1
kind: Certificate
metadata:
  name: {{ include "webhook.rootCACertificate" . }}
  namespace: {{ .Release.Namespace | quote }}
  labels:
    app: {{ include "webhook.name" . }}
    chart: {{ include "webhook.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
spec:
  secretName: {{ include "webhook.rootCACertificate" . }}
  duration: 43800h # 5y
  issuerRef:
    name: {{ include "webhook.selfSignedIssuer" . }}
  commonName: "ca.webhook.cert-manager"
  isCA: true

---

# Create an Issuer that uses the above generated CA certificate to issue certs
apiVersion: certmanager.k8s.io/v1alpha1
kind: Issuer
metadata:
  name: {{ include "webhook.rootCAIssuer" . }}
  namespace: {{ .Release.Namespace | quote }}
  labels:
    app: {{ include "webhook.name" . }}
    chart: {{ include "webhook.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
spec:
  ca:
    secretName: {{ include "webhook.rootCACertificate" . }}

---

# Finally, generate a serving certificate for the webhook to use
apiVersion: certmanager.k8s.io/v1alpha1
kind: Certificate
metadata:
  name: {{ include "webhook.servingCertificate" . }}
  namespace: {{ .Release.Namespace | quote }}
  labels:
    app: {{ include "webhook.name" . }}
    chart: {{ include "webhook.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
spec:
  secretName: {{ include "webhook.servingCertificate" . }}
  duration: 8760h # 1y
  issuerRef:
    name: {{ include "webhook.rootCAIssuer" . }}
  dnsNames:
  - {{ include "webhook.fullname" . }}
  - {{ include "webhook.fullname" . }}.{{ .Release.Namespace }}
  - {{ include "webhook.fullname" . }}.{{ .Release.Namespace }}.svc
 # rbac.yaml
{{- if .Values.rbac.create -}}
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRole
metadata:
  name: {{ template "cert-manager.fullname" . }}
  labels:
    app: {{ template "cert-manager.name" . }}
    chart: {{ template "cert-manager.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
rules:
  - apiGroups: ["certmanager.k8s.io"]
    resources: ["certificates", "certificates/finalizers", "issuers", "clusterissuers", "orders", "orders/finalizers", "challenges"]
    verbs: ["*"]
  - apiGroups: [""]
    resources: ["configmaps", "secrets", "events", "services", "pods"]
    verbs: ["*"]
  - apiGroups: ["extensions"]
    resources: ["ingresses"]
    verbs: ["*"]
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: {{ template "cert-manager.fullname" . }}
  labels:
    app: {{ template "cert-manager.name" . }}
    chart: {{ template "cert-manager.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: {{ template "cert-manager.fullname" . }}
subjects:
  - name: {{ template "cert-manager.serviceAccountName" . }}
    namespace: {{ .Release.Namespace | quote }}
    kind: ServiceAccount
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: {{ template "cert-manager.fullname" . }}-view
  labels:
    app: {{ template "cert-manager.name" . }}
    chart: {{ template "cert-manager.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
    rbac.authorization.k8s.io/aggregate-to-view: "true"
    rbac.authorization.k8s.io/aggregate-to-edit: "true"
    rbac.authorization.k8s.io/aggregate-to-admin: "true"
rules:
  - apiGroups: ["certmanager.k8s.io"]
    resources: ["certificates", "issuers"]
    verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: {{ template "cert-manager.fullname" . }}-edit
  labels:
    app: {{ template "cert-manager.name" . }}
    chart: {{ template "cert-manager.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
    rbac.authorization.k8s.io/aggregate-to-edit: "true"
    rbac.authorization.k8s.io/aggregate-to-admin: "true"
rules:
  - apiGroups: ["certmanager.k8s.io"]
    resources: ["certificates", "issuers"]
    verbs: ["create", "delete", "deletecollection", "patch", "update"]
{{- end -}}
 # service.yaml
apiVersion: v1
kind: Service
metadata:
  name: {{ include "webhook.fullname" . }}
  namespace: {{ .Release.Namespace | quote }}
  labels:
    app: {{ include "webhook.name" . }}
    chart: {{ include "webhook.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
spec:
  type: ClusterIP
  ports:
  - name: https
    port: 443
    targetPort: 6443
  selector:
    app: {{ include "webhook.name" . }}
    release: {{ .Release.Name }}
 # serviceaccount.yaml
{{- if .Values.serviceAccount.create -}}
apiVersion: v1
kind: ServiceAccount
{{- if .Values.global.imagePullSecrets }}
imagePullSecrets: {{ toYaml .Values.global.imagePullSecrets | nindent 2 }}
{{- end }}
metadata:
  name: {{ template "cert-manager.serviceAccountName" . }}
  namespace: {{ .Release.Namespace | quote }}
  labels:
    app: {{ template "cert-manager.name" . }}
    chart: {{ template "cert-manager.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
{{- end -}}
 # validating-webhook.yaml
apiVersion: admissionregistration.k8s.io/v1beta1
kind: ValidatingWebhookConfiguration
metadata:
  name: {{ include "webhook.fullname" . }}
  labels:
    app: {{ include "webhook.name" . }}
    chart: {{ include "webhook.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
webhooks:
  - name: certificates.admission.certmanager.k8s.io
    namespaceSelector:
      matchExpressions:
      - key: "certmanager.k8s.io/disable-validation"
        operator: "NotIn"
        values:
        - "true"
      - key: "name"
        operator: "NotIn"
        values:
        - {{ .Release.Namespace }}
    rules:
      - apiGroups:
          - "certmanager.k8s.io"
        apiVersions:
          - v1alpha1
        operations:
          - CREATE
          - UPDATE
        resources:
          - certificates
    failurePolicy: Fail
    clientConfig:
      service:
        name: kubernetes
        namespace: default
        path: /apis/admission.certmanager.k8s.io/v1beta1/certificates
  - name: issuers.admission.certmanager.k8s.io
    namespaceSelector:
      matchExpressions:
      - key: "certmanager.k8s.io/disable-validation"
        operator: "NotIn"
        values:
        - "true"
      - key: "name"
        operator: "NotIn"
        values:
        - {{ .Release.Namespace }}
    rules:
      - apiGroups:
          - "certmanager.k8s.io"
        apiVersions:
          - v1alpha1
        operations:
          - CREATE
          - UPDATE
        resources:
          - issuers
    failurePolicy: Fail
    clientConfig:
      service:
        name: kubernetes
        namespace: default
        path: /apis/admission.certmanager.k8s.io/v1beta1/issuers
  - name: clusterissuers.admission.certmanager.k8s.io
    namespaceSelector:
      matchExpressions:
      - key: "certmanager.k8s.io/disable-validation"
        operator: "NotIn"
        values:
        - "true"
      - key: "name"
        operator: "NotIn"
        values:
        - {{ .Release.Namespace }}
    rules:
      - apiGroups:
          - "certmanager.k8s.io"
        apiVersions:
          - v1alpha1
        operations:
          - CREATE
          - UPDATE
        resources:
          - clusterissuers
    failurePolicy: Fail
    clientConfig:
      service:
        name: kubernetes
        namespace: default
        path: /apis/admission.certmanager.k8s.io/v1beta1/clusterissuers

global:
  ## Reference to one or more secrets to be used when pulling images
  ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/
  ##
  imagePullSecrets: []
  # - name: "image-pull-secret"

  # Optional priority class to be used for the cert-manager pods
  priorityClassName: ""

replicaCount: 1

strategy: {}
  # type: RollingUpdate
  # rollingUpdate:
  #   maxSurge: 0
  #   maxUnavailable: 1

podAnnotations: {}

# Optional additional arguments for webhook
extraArgs: []

resources: {}
  # requests:
  #   cpu: 10m
  #   memory: 32Mi

image:
  repository: quay.io/jetstack/cert-manager-webhook
  tag: v0.6.2
  pullPolicy: IfNotPresent

caSyncImage:
  repository: quay.io/munnerz/apiextensions-ca-helper
  tag: v0.1.0
  pullPolicy: IfNotPresent
