# _helpers.tpl
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "ambassador.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).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "ambassador.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 "ambassador.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}}
{{- end -}}

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

{{/*
Define the http port of the Ambassador service
*/}}
{{- define "ambassador.servicePort" -}}
{{- range .Values.service.ports -}}
{{- if (eq .name "http") -}}
{{ default .port }}
{{- end -}}
{{- end -}}
{{- end -}}
 # admin-service.yaml
{{- if .Values.adminService.create -}}
apiVersion: v1
kind: Service
metadata:
  name: {{ include "ambassador.fullname" . }}-admin
  labels:
    app.kubernetes.io/name: {{ include "ambassador.name" . }}
    helm.sh/chart: {{ include "ambassador.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/part-of: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  {{- if .Values.extraLabels }}
    {{- toYaml .Values.extraLabels | nindent 4 }}
  {{- end }}
  {{- with .Values.adminService.annotations }}
  annotations:
    {{- toYaml . | nindent 4 }}
  {{- end }}
spec:
  type: {{ .Values.adminService.type }}
  ports:
    - port: {{ .Values.adminService.port }}
      targetPort: admin
      protocol: TCP
      name: admin
      {{- if (and (eq .Values.adminService.type "NodePort") (not (empty .Values.adminService.nodePort))) }}
      nodePort: {{ .Values.adminService.nodePort }}
      {{- end }}
  selector:
    app.kubernetes.io/name: {{ include "ambassador.name" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
  {{- if eq .Values.adminService.type "LoadBalancer" }}
  {{- if not (empty .Values.adminService.loadBalancerIP) }}
  loadBalancerIP: {{ .Values.adminService.loadBalancerIP | quote }}
  {{- end }}
  {{- if not (empty .Values.adminService.loadBalancerSourceRanges) }}
  loadBalancerSourceRanges:
    {{- toYaml .Values.adminService.loadBalancerSourceRanges | nindent 4 }}
  {{- end }}
  {{- end }}
{{- end -}}
 # ambassador-devportal.yaml
{{ if and .Values.pro.enabled .Values.pro.devPortal.enabled  }}
{{- if .Values.crds.enabled }}
---
apiVersion: getambassador.io/v1
kind: Mapping
metadata:
  name: {{ include "ambassador.fullname" . }}-pro-devportal
spec:
  {{- if hasKey .Values.env "AMBASSADOR_ID" }}
  ambassador_id: {{ .Values.env.AMBASSADOR_ID | quote }}
  {{- end }}
  prefix: /docs/
  rewrite: ""
  service: 127.0.0.1:{{ .Values.pro.ports.auth }}
---
apiVersion: getambassador.io/v1
kind: Mapping
metadata:
  name: {{ include "ambassador.fullname" . }}-pro-devportal-api
spec:
  {{- if hasKey .Values.env "AMBASSADOR_ID" }}
  ambassador_id: {{ .Values.env.AMBASSADOR_ID | quote }}
  {{- end }}
  prefix: /openapi/
  rewrite: ""
  service: 127.0.0.1:{{ .Values.pro.ports.auth }}
{{- end }}
---
apiVersion: getambassador.io/v1beta2
kind: FilterPolicy
metadata:
  name: {{ include "ambassador.fullname" . }}-pro-internal-access-control
spec:
  {{- if hasKey .Values.env "AMBASSADOR_ID" }}
  ambassador_id: {{ .Values.env.AMBASSADOR_ID | quote }}
  {{- end }}
  rules:
    - host: "*"
      path: "*/.ambassador-internal/*"
      filters:
        - name: ambassador-pro-internal-access-control
---
apiVersion: getambassador.io/v1beta2
kind: Filter
metadata:
  name: {{ include "ambassador.fullname" . }}-pro-internal-access-control
spec:
  {{- if hasKey .Values.env "AMBASSADOR_ID" }}
  ambassador_id: {{ .Values.env.AMBASSADOR_ID | quote }}
  {{- end }}
  Internal: {}
{{ end }} # ambassador-pro-auth.yaml
{{ if and .Values.pro.enabled .Values.pro.authService.enabled }}

{{- if .Values.crds.enabled }}
---
apiVersion: getambassador.io/v1
kind: AuthService
metadata:
  name: {{ include "ambassador.fullname" . }}-pro-auth
spec:
  proto: grpc
  {{- if hasKey .Values.env "AMBASSADOR_ID" }}
  ambassador_id: {{ .Values.env.AMBASSADOR_ID | quote }}
  {{- end }}
  auth_service: 127.0.0.1:{{ .Values.pro.ports.auth }}
  {{- if .Values.pro.authService.optional_configurations }}
  {{- toYaml .Values.pro.authService.optional_configurations | nindent 2}}
  {{- end }}
---
apiVersion: getambassador.io/v1
kind: Mapping
metadata:
  name: {{ include "ambassador.fullname" . }}-pro-callback-mapping
spec:
  {{- if hasKey .Values.env "AMBASSADOR_ID" }}
  ambassador_id: {{ .Values.env.AMBASSADOR_ID | quote }}
  {{- end }}
  prefix: /callback
  service: NoTaReAlSeRvIcE
---
apiVersion: getambassador.io/v1
kind: Mapping
metadata:
  name: {{ include "ambassador.fullname" . }}-pro-mapping
spec:
  {{- if hasKey .Values.env "AMBASSADOR_ID" }}
  ambassador_id: {{ .Values.env.AMBASSADOR_ID | quote }}
  {{- end }}
  prefix: /.ambassador/
  rewrite: ""
  service: 127.0.0.1:{{ .Values.pro.ports.auth }}
{{- end }}
{{ end }}
 # ambassador-pro-license-key-secret.yaml
{{- if and .Values.pro.enabled .Values.pro.licenseKey.secret.create -}}
apiVersion: v1
kind: Secret
metadata:
  name: ambassador-pro-license-key
type: Opaque
data:
  key: {{ .Values.pro.licenseKey.value | b64enc }}
{{- end -}}
 # ambassador-pro-ratelimit.yaml
{{ if and .Values.pro.enabled .Values.crds.enabled  }}
---
apiVersion: getambassador.io/v1
kind: RateLimitService
metadata:
  name: {{ include "ambassador.fullname" . }}-pro-ratelimit
spec:
  {{- if hasKey .Values.env "AMBASSADOR_ID" }}
  ambassador_id: {{ .Values.env.AMBASSADOR_ID | quote }}
  {{- end }}
  service: 127.0.0.1:{{ .Values.pro.ports.ratelimit }}
{{ end }} # ambassador-pro-redis.yaml
{{ if and .Values.pro.enabled }}
---
apiVersion: v1
kind: Service
metadata:
  name: {{ include "ambassador.fullname" . }}-pro-redis
  labels:
    app.kubernetes.io/name: {{ include "ambassador.fullname" . }}-pro-redis
    app.kubernetes.io/part-of: {{ .Release.Name }}
    helm.sh/chart: {{ include "ambassador.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
    {{- if .Values.extraLabels }}
      {{- toYaml .Values.extraLabels | nindent 4 }}
    {{- end }}
  annotations:
    {{- toYaml .Values.pro.rateLimit.redis.annotations.service | nindent 4}}
spec:
  type: ClusterIP
  ports:
  - port: 6379
    targetPort: 6379
  selector:
    app.kubernetes.io/name: {{ include "ambassador.fullname" . }}-pro-redis
    app.kubernetes.io/instance: {{ .Release.Name }}
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "ambassador.fullname" . }}-pro-redis
  labels:
    app.kubernetes.io/name: {{ include "ambassador.fullname" . }}-pro-redis
    app.kubernetes.io/part-of: {{ .Release.Name }}
    helm.sh/chart: {{ include "ambassador.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  {{- if .Values.extraLabels }}
    {{- toYaml .Values.extraLabels | nindent 4 }}
  {{- end }}
  annotations:
    {{- toYaml .Values.pro.rateLimit.redis.annotations.deployment | nindent 4}}
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ include "ambassador.fullname" . }}-pro-redis
      app.kubernetes.io/instance: {{ .Release.Name }}
  template:
    metadata:
      labels:
        app.kubernetes.io/name: {{ include "ambassador.fullname" . }}-pro-redis
        app.kubernetes.io/instance: {{ .Release.Name }}
      {{- if .Values.extraLabels }}
        {{- toYaml .Values.extraLabels | nindent 8 }}
      {{- end }}
    spec:
      containers:
      - name: redis
        image: redis:5.0.1
        resources:
        {{- toYaml .Values.pro.rateLimit.redis.resources | nindent 10 }}
      restartPolicy: Always
{{ end }}
 # ambassador-pro-service.yaml
{{ if and .Values.pro.enabled (not .Values.crds.enabled) }}
---
apiVersion: v1
kind: Service
metadata:
  name: {{ include "ambassador.fullname" . }}-pro
  labels:
    service: ambassador-pro
    app.kubernetes.io/name: {{ include "ambassador.name" . }}
    app.kubernetes.io/part-of: {{ .Release.Name }}
    helm.sh/chart: {{ include "ambassador.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
    {{- if .Values.extraLabels }}
      {{- toYaml .Values.extraLabels | nindent 4 }}
    {{- end }}
  annotations:
    getambassador.io/config: |
      {{- if .Values.pro.authService.enabled }}
      ---
      apiVersion: ambassador/v1
      kind: AuthService
      name: {{ include "ambassador.fullname" . }}-pro-auth
      proto: grpc
      {{- if hasKey .Values.env "AMBASSADOR_ID" }}
      ambassador_id: {{ .Values.env.AMBASSADOR_ID | quote }}
      {{- end }}
      auth_service: 127.0.0.1:{{ .Values.pro.ports.auth }}
      {{- toYaml .Values.pro.authService.optional_configurations | nindent 6}}
      ---
      # This mapping needs to exist, but is never actually followed.
      apiVersion: ambassador/v1
      kind: Mapping
      name: {{ include "ambassador.fullname" . }}-pro-callback_mapping
      {{- if hasKey .Values.env "AMBASSADOR_ID" }}
      ambassador_id: {{ .Values.env.AMBASSADOR_ID | quote }}
      {{- end }}
      prefix: /callback
      service: NoTaReAlSeRvIcE
      {{- end }}
      {{- if .Values.pro.rateLimit.enabled }}
      ---
      apiVersion: ambassador/v1
      kind: RateLimitService
      name: {{ include "ambassador.fullname" . }}-pro-ratelimit
      {{- if hasKey .Values.env "AMBASSADOR_ID" }}
      ambassador_id: {{ .Values.env.AMBASSADOR_ID | quote }}
      {{- end }}
      service: 127.0.0.1:{{ .Values.pro.ports.ratelimit }}
      {{- end }}
      {{- if .Values.pro.devPortal.enabled }}
      ---
      apiVersion: ambassador/v1
      kind: Mapping
      name: {{ include "ambassador.fullname" . }}-pro-devportal
      {{- if hasKey .Values.env "AMBASSADOR_ID" }}
      ambassador_id: {{ .Values.env.AMBASSADOR_ID | quote }}
      {{- end }}
      prefix: /docs/
      rewrite: ""
      service: 127.0.0.1:{{ .Values.pro.ports.auth }}
      ---
      apiVersion: ambassador/v1
      kind: Mapping
      name: {{ include "ambassador.fullname" . }}-pro-devportal-api
      {{- if hasKey .Values.env "AMBASSADOR_ID" }}
      ambassador_id: {{ .Values.env.AMBASSADOR_ID | quote }}
      {{- end }}
      prefix: /openapi/
      rewrite: ""
      service: 127.0.0.1:{{ .Values.pro.ports.auth }}
      {{- end }}
spec:
  ports:
  - name: http
    port: 80
{{ end }}
 # config.yaml
{{- if .Values.ambassadorConfig }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: '{{ include "ambassador.fullname" . }}-file-config'
  labels:
    app.kubernetes.io/name: {{ include "ambassador.name" . }}
    app.kubernetes.io/part-of: {{ .Release.Name }}
    helm.sh/chart: {{ include "ambassador.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  {{- if .Values.extraLabels }}
    {{- toYaml .Values.extraLabels | nindent 4 }}
  {{- end }}
data:
  ambassadorConfig: |-
    {{- .Values.ambassadorConfig | nindent 4 }}
{{- end }}
 # crd-delete.yaml
{{- if and .Values.crds.enabled (not .Values.crds.keep)}}
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ include "ambassador.fullname" . }}-crd-cleanup
  namespace: {{ .Release.Namespace }}
  annotations:
    "helm.sh/hook": pre-delete
    "helm.sh/hook-weight": "3"
    "helm.sh/hook-delete-policy": hook-succeeded
  labels:
    app.kubernetes.io/name: {{ include "ambassador.name" . }}
    app.kubernetes.io/part-of: {{ .Release.Name }}
    helm.sh/chart: {{ include "ambassador.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  {{- if .Values.extraLabels }}
    {{- toYaml .Values.extraLabels | nindent 4 }}
  {{- end }}
spec:
  template:
    metadata:
      name: {{ include "ambassador.fullname" . }}-crd-cleanup
      labels:
        app.kubernetes.io/name: {{ include "ambassador.name" . }}
        app.kubernetes.io/part-of: {{ .Release.Name }}
        helm.sh/chart: {{ include "ambassador.chart" . }}
        app.kubernetes.io/instance: {{ .Release.Name }}
        app.kubernetes.io/managed-by: {{ .Release.Service }}
      {{- if .Values.extraLabels }}
        {{- toYaml .Values.extraLabels | nindent 8 }}
      {{- end }}
    spec:
      {{- if .Values.rbac.create }}
      serviceAccountName: {{ include "ambassador.serviceAccountName" . }}
      {{- end }}
      containers:
        - name: kubectl
          image: "k8s.gcr.io/hyperkube:v1.12.1"
          command:
          - /bin/sh
          - -c
          - >
              kubectl delete crds -l app.kubernetes.io/name=ambassador
      restartPolicy: OnFailure
{{- end }}
 # crds-rbac.yaml
{{- if .Values.crds.enabled }}
{{- if .Values.rbac.create }}
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRole
metadata:
  name: {{ include "ambassador.fullname" . }}-crds
  labels:
    app.kubernetes.io/name: {{ include "ambassador.name" . }}
    helm.sh/chart: {{ include "ambassador.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  {{- if .Values.extraLabels }}
    {{- toYaml .Values.extraLabels | nindent 4 }}
  {{- end }}
rules:
  - apiGroups: [ "apiextensions.k8s.io" ]
    resources:
    - customresourcedefinitions
    resourceNames:
    - authservices.getambassador.io
    - mappings.getambassador.io
    - modules.getambassador.io
    - ratelimitservices.getambassador.io
    - tcpmappings.getambassador.io
    - tlscontexts.getambassador.io
    - tracingservices.getambassador.io
    - kubernetesendpointresolvers.getambassador.io
    - kubernetesserviceresolvers.getambassador.io
    - consulresolvers.getambassador.io
    - logservices.getambassador.io
    {{- if .Values.pro.enabled }}
    - filters.getambassador.io
    - filterpolicies.getambassador.io
    - ratelimits.getambassador.io
    {{- end }}
    verbs: ["get", "list", "watch", "delete"]
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: {{ include "ambassador.fullname" . }}-crds
  labels:
    app.kubernetes.io/name: {{ include "ambassador.name" . }}
    helm.sh/chart: {{ include "ambassador.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  {{- if .Values.extraLabels }}
    {{- toYaml .Values.extraLabels | nindent 4 }}
  {{- end }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: {{ include "ambassador.fullname" . }}-crds
subjects:
  - name: {{ include "ambassador.serviceAccountName" . }}
    namespace: {{ .Release.Namespace | quote }}
    kind: ServiceAccount
{{- end }}
{{- end }}
 # crds.yaml
{{- if .Values.crds.create }}
{{- range $path, $bytes := .Files.Glob "crds/*.yaml" }}
{{ $.Files.Get $path }}
---
{{- end }}
{{- end }}
 # deployment.yaml
apiVersion: apps/v1
{{- if .Values.daemonSet }}
kind: DaemonSet
{{- else }}
kind: Deployment
{{- end }}
metadata:
  name: {{ include "ambassador.fullname" . }}
  labels:
    app.kubernetes.io/name: {{ include "ambassador.name" . }}
    app.kubernetes.io/part-of: {{ .Release.Name }}
    helm.sh/chart: {{ include "ambassador.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
    {{- if .Values.extraLabels }}
      {{- toYaml .Values.extraLabels | nindent 4 }}
    {{- end }}
    {{- if .Values.deploymentAnnotations }}
  annotations:
      {{- toYaml .Values.deploymentAnnotations | nindent 4 }}
    {{- end }}
spec:
{{- if and (not .Values.autoscaling.enabled) (not .Values.daemonSet) }}
  replicas: {{ .Values.replicaCount }}
{{- end }}
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ include "ambassador.name" . }}
      app.kubernetes.io/instance: {{ .Release.Name }}
  template:
    metadata:
      labels:
        app.kubernetes.io/name: {{ include "ambassador.name" . }}
        app.kubernetes.io/part-of: {{ .Release.Name }}
        app.kubernetes.io/instance: {{ .Release.Name }}
      {{- if .Values.podLabels }}
        {{- toYaml .Values.podLabels | nindent 8 }}
      {{- end }}
      {{- if .Values.extraLabels }}
        {{- toYaml .Values.extraLabels | nindent 8 }}
      {{- end }}
      annotations:
        checksum/config: {{ include (print $.Template.BasePath "/config.yaml") . | sha256sum }}
      {{- if .Values.podAnnotations }}
        {{- toYaml .Values.podAnnotations | nindent 8 }}
      {{- end }}
    spec:
      {{- with .Values.securityContext }}
      securityContext:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      serviceAccountName: {{ include "ambassador.serviceAccountName" . }}
      {{- if .Values.priorityClassName }}
      priorityClassName: {{ .Values.priorityClassName | quote }}
      {{- end }}
      volumes:
        - name: ambassador-pod-info
          downwardAPI:
            items:
              - fieldRef:
                  fieldPath: metadata.labels
                path: labels
        {{- if .Values.prometheusExporter.enabled }}
        - name: stats-exporter-mapping-config
          configMap:
            name: {{ include "ambassador.fullname" . }}-exporter-config
            items:
            - key: exporterConfiguration
              path: mapping-config.yaml
        {{- end }}
        {{- if .Values.ambassadorConfig }}
        - name: ambassador-config
          configMap:
            name: {{ include "ambassador.fullname" . }}-file-config
            items:
            - key: ambassadorConfig
              path: ambassador-config.yaml
        {{- end }}
      {{- with .Values.volumes }}
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with .Values.initContainers }}
      initContainers:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      containers:
        {{- if .Values.prometheusExporter.enabled }}
        - name: prometheus-exporter
          image: "{{ .Values.prometheusExporter.repository }}:{{ .Values.prometheusExporter.tag }}"
          imagePullPolicy: {{ .Values.prometheusExporter.pullPolicy }}
          ports:
            - name: metrics
              containerPort: 9102
            - name: listener
              containerPort: 8125
          args:
            - --statsd.listen-udp=:8125
            - --web.listen-address=:9102
            - --statsd.mapping-config=/statsd-exporter/mapping-config.yaml
          volumeMounts:
            - name: stats-exporter-mapping-config
              mountPath: /statsd-exporter/
              readOnly: true
          resources:
            {{- toYaml .Values.prometheusExporter.resources | nindent 12 }}
        {{- end }}
        - name: {{ .Chart.Name }}
          {{- if and .Values.pro.enabled (semverCompare ">0.6.0" .Values.pro.image.tag) }}
          image: "{{ .Values.pro.image.repository }}:amb-core-{{ .Values.pro.image.tag }}"
          {{ else }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          {{- end }}
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          ports:
            {{- range .Values.service.ports }}
            - name: {{ .name }}
              containerPort: {{ .targetPort }}
              {{- if .protocol }}
              protocol: {{ .protocol }}
              {{- end }}
            {{- end}}
            - name: admin
              containerPort: 8877
          env:
            - name: HOST_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.hostIP
            {{- if and .Values.pro.enabled (semverCompare ">0.6.0" .Values.pro.image.tag) }}
            - name: AMBASSADOR_LICENSE_KEY
            {{- if .Values.pro.licenseKey.secret.enabled }}
              valueFrom:
                secretKeyRef:
                  name: ambassador-pro-license-key
                  key: key
            {{ else }}
              value: {{ .Values.pro.licenseKey.value }}
            {{- end }}
            {{- end }}
            {{- if .Values.prometheusExporter.enabled }}
            - name: STATSD_ENABLED
              value: "true"
            - name: STATSD_HOST
              value: "localhost"
            {{- end }}
            {{- if .Values.scope.singleNamespace }}
            - name: AMBASSADOR_SINGLE_NAMESPACE
              value: "YES"
            {{- end }}
            - name: AMBASSADOR_NAMESPACE
              {{- if .Values.namespace }}
              value: {{ .Values.namespace.name | quote }}
              {{ else }}
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
              {{- end -}}
            {{- if .Values.env }}
            {{- range $key,$value := .Values.env }}
            - name: {{ $key | upper | quote}}
              value: {{ $value | quote}}
            {{- end }}
            {{- end }}
          livenessProbe:
            httpGet:
              path: /ambassador/v0/check_alive
              port: admin
            initialDelaySeconds: {{ .Values.livenessProbe.initialDelaySeconds }}
            periodSeconds: {{ .Values.livenessProbe.periodSeconds }}
            failureThreshold: {{ .Values.livenessProbe.failureThreshold }}
          readinessProbe:
            httpGet:
              path: /ambassador/v0/check_ready
              port: admin
            initialDelaySeconds: {{ .Values.readinessProbe.initialDelaySeconds }}
            periodSeconds: {{ .Values.readinessProbe.periodSeconds }}
            failureThreshold: {{ .Values.readinessProbe.failureThreshold }}
          volumeMounts:
            - name: ambassador-pod-info
              mountPath: /tmp/ambassador-pod-info
              readOnly: true
          {{- if .Values.ambassadorConfig }}
            - name: ambassador-config
              mountPath: /ambassador/ambassador-config/ambassador-config.yaml
              subPath: ambassador-config.yaml
          {{- end }}
          {{- with .Values.volumeMounts }}
            {{- toYaml . | nindent 12 }}
          {{- end }}
          resources:
            {{- toYaml .Values.resources | nindent 12 }}
        {{- if .Values.pro.enabled }}
        - name: ambassador-pro
          {{ if .Values.pro.image.customBuildTag }}
          image: "{{ .Values.pro.image.repository }}:{{ .Values.pro.image.customBuildTag }}"
          {{ else }}
          image: "{{ .Values.pro.image.repository }}:amb-sidecar-{{ .Values.pro.image.tag }}"
          {{ end }}
          ports:
          - name: grpc-auth
            containerPort: {{ .Values.pro.ports.auth }}
          - name: grpc-ratelimit
            containerPort: {{ .Values.pro.ports.ratelimit }}
          env:
          - name: REDIS_SOCKET_TYPE
            value: tcp
          - name: REDIS_URL
            value: {{ include "ambassador.fullname" . }}-pro-redis:6379
          - name: APRO_HTTP_PORT
            value: "{{ .Values.pro.ports.auth }}"
          - name: APP_LOG_LEVEL
            value: "{{ .Values.pro.logLevel  }}"
          - name: AMBASSADOR_NAMESPACE
          {{- if .Values.namespace }}
            value: {{ .Values.namespace.name | quote }}
          {{ else }}
            valueFrom:
              fieldRef:
                fieldPath: metadata.namespace
          {{- end }}
          {{- if hasKey .Values.env "AMBASSADOR_ID" }}
          - name: "AMBASSADOR_ID"
            value: {{ .Values.env.AMBASSADOR_ID | quote }}
          {{- end }}
          - name: AMBASSADOR_LICENSE_KEY
          {{- if .Values.pro.licenseKey.secret.enabled }}
            valueFrom:
              secretKeyRef:
                name: ambassador-pro-license-key
                key: key
          {{ else }}
            value: {{ .Values.pro.licenseKey.value }}
          {{- end }}
          {{- if .Values.pro.env }}
          {{- range $key, $value := .Values.pro.env }}
          {{- if eq $key "AMBASSADOR_ID" }}
          {{- else}}
          - name: {{ $key | upper | quote }}
            value: {{ $value | quote }}
          {{- end }}
          {{- end }}
          {{- end }}
          resources:
            {{- toYaml .Values.pro.resources | nindent 12 }}
        {{- end }}
      {{- with .Values.sidecarContainers }}
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with .Values.nodeSelector }}
      nodeSelector:
        {{- toYaml . | nindent 8 }}
      {{- end }}
    {{- with .Values.affinity }}
      affinity:
        {{- toYaml . | nindent 8 }}
    {{- end }}
    {{- with .Values.tolerations }}
      tolerations:
        {{- toYaml . | nindent 8 }}
    {{- end }}
      imagePullSecrets:
        {{- toYaml .Values.imagePullSecrets | nindent 8 }}
      dnsPolicy: {{ .Values.dnsPolicy }}
      hostNetwork: {{ .Values.hostNetwork }}
 # exporter-config.yaml
{{- if .Values.prometheusExporter.enabled }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: '{{ include "ambassador.fullname" . }}-exporter-config'
  labels:
    app.kubernetes.io/name: {{ include "ambassador.name" . }}
    app.kubernetes.io/part-of: {{ .Release.Name }}
    helm.sh/chart: {{ include "ambassador.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  {{- if .Values.extraLabels }}
    {{- toYaml .Values.extraLabels | nindent 4 }}
  {{- end }}
data:
  exporterConfiguration:
{{- if .Values.prometheusExporter.configuration }} |
    {{- .Values.prometheusExporter.configuration | nindent 4 }}
{{- else }} ''
{{- end }}
{{- end }}
 # hpa.yaml
{{- if and .Values.autoscaling.enabled (not .Values.daemonSet) }}
apiVersion: autoscaling/v2beta2
kind: HorizontalPodAutoscaler
metadata:
  name: {{ include "ambassador.fullname" . }}
  labels:
    app.kubernetes.io/name: {{ include "ambassador.name" . }}
    app.kubernetes.io/part-of: {{ .Release.Name }}
    helm.sh/chart: {{ include "ambassador.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  {{- if .Values.extraLabels }}
    {{- toYaml .Values.extraLabels | nindent 4 }}
  {{- end }}
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: {{ include "ambassador.fullname" . }}
  minReplicas: {{ .Values.autoscaling.minReplicas }}
  maxReplicas: {{ .Values.autoscaling.maxReplicas }}
  metrics:
    {{- toYaml .Values.autoscaling.metrics | nindent 4 }}
{{- end }}
 # pdb.yaml
{{- if .Values.podDisruptionBudget }}
apiVersion: policy/v1beta1
kind: PodDisruptionBudget
metadata:
  name: {{ include "ambassador.fullname" . }}
  labels:
    app.kubernetes.io/name: {{ include "ambassador.name" . }}
    app.kubernetes.io/part-of: {{ .Release.Name }}
    helm.sh/chart: {{ include "ambassador.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  {{- if .Values.extraLabels }}
    {{- toYaml .Values.extraLabels | nindent 4 }}
  {{- end }}
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ include "ambassador.name" . }}
      app.kubernetes.io/part-of: {{ .Release.Name }}
{{ toYaml .Values.podDisruptionBudget | indent 2 }}
{{- end }}
 # rbac.yaml
{{- if .Values.rbac.create -}}
apiVersion: rbac.authorization.k8s.io/v1beta1
{{- if .Values.scope.singleNamespace }}
kind: Role
{{- else }}
kind: ClusterRole
{{- end }}
metadata:
  name: {{ include "ambassador.fullname" . }}
  labels:
    app.kubernetes.io/name: {{ include "ambassador.name" . }}
    app.kubernetes.io/part-of: {{ .Release.Name }}
    helm.sh/chart: {{ include "ambassador.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  {{- if .Values.extraLabels }}
    {{- toYaml .Values.extraLabels | nindent 4 }}
  {{- end }}
rules:
  - apiGroups: [""]
    resources:
    {{- if not .Values.scope.singleNamespace }}
    - namespaces
    {{- end }}
    - services
    - secrets
    - endpoints
    verbs: ["get", "list", "watch"]
  - apiGroups: [ "getambassador.io" ]
    resources: [ "*" ]
    verbs: ["get", "list", "watch"]
  - apiGroups: [ "apiextensions.k8s.io" ]
    resources: [ "customresourcedefinitions" ]
    verbs: ["get", "list", "watch"]
  - apiGroups: [ "networking.internal.knative.dev"]
    resources: [ "clusteringresses" ]
    verbs: ["get", "list", "watch"]
  - apiGroups: [ "extensions" ]
    resources: [ "ingresses" ]
    verbs: ["get", "list", "watch"]
  - apiGroups: [ "extensions" ]
    resources: [ "ingresses/status" ]
    verbs: ["update"]
  {{- if .Values.pro.enabled }}
  - apiGroups: [""]
    resources: [ "secrets" ]
    verbs: ["get", "list", "watch", "create"]
  {{- end }}
  {{- if .Values.rbac.podSecurityPolicies }}
  - apiGroups: ['policy']
    resources: ['podsecuritypolicies']
    verbs: ['use']
    resourceNames:
      {{- toYaml .Values.rbac.podSecurityPolicies | nindent 6 }}
  {{- end }}
---
apiVersion: rbac.authorization.k8s.io/v1beta1
{{- if .Values.scope.singleNamespace }}
kind: RoleBinding
{{- else }}
kind: ClusterRoleBinding
{{- end }}
metadata:
  name: {{ include "ambassador.fullname" . }}
  labels:
    app.kubernetes.io/name: {{ include "ambassador.name" . }}
    app.kubernetes.io/part-of: {{ .Release.Name }}
    helm.sh/chart: {{ include "ambassador.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  {{- if .Values.extraLabels }}
    {{- toYaml .Values.extraLabels | nindent 4 }}
  {{- end }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  {{- if .Values.scope.singleNamespace }}
  kind: Role
  {{- else }}
  kind: ClusterRole
  {{- end }}
  name: {{ include "ambassador.fullname" . }}
subjects:
  - name: {{ include "ambassador.serviceAccountName" . }}
    namespace: {{ .Release.Namespace | quote }}
    kind: ServiceAccount
{{- end -}}
 # service.yaml
apiVersion: v1
kind: Service
metadata:
  name: {{ include "ambassador.fullname" . }}
  labels:
    app.kubernetes.io/name: {{ include "ambassador.name" . }}
    app.kubernetes.io/part-of: {{ .Release.Name }}
    helm.sh/chart: {{ include "ambassador.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
    app.kubernetes.io/component: ambassador-service
  {{- if .Values.extraLabels }}
    {{- toYaml .Values.extraLabels | nindent 4 }}
  {{- end }}
  {{- with .Values.service.annotations }}
  annotations:
    {{- toYaml . | nindent 4 }}
  {{- end }}
spec:
  type: {{ .Values.service.type }}
  {{- if .Values.service.loadBalancerIP }}
  loadBalancerIP: "{{ .Values.service.loadBalancerIP }}"
  {{- end }}
  {{- if .Values.service.externalTrafficPolicy }}
  externalTrafficPolicy: "{{ .Values.service.externalTrafficPolicy }}"
  {{- end }}
  ports:
    {{- toYaml .Values.service.ports | nindent 4 }}
  selector:
    app.kubernetes.io/name: {{ include "ambassador.name" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
  {{- with .Values.service.loadBalancerSourceRanges }}
  loadBalancerSourceRanges:
    {{- toYaml . | nindent 4 }}
  {{- end }}
 # serviceaccount.yaml
{{- if .Values.serviceAccount.create -}}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ include "ambassador.serviceAccountName" . }}
  labels:
    app.kubernetes.io/name: {{ include "ambassador.name" . }}
    app.kubernetes.io/part-of: {{ .Release.Name }}
    helm.sh/chart: {{ include "ambassador.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  {{- if .Values.extraLabels }}
    {{- toYaml .Values.extraLabels | nindent 4 }}
  {{- end }}
{{- end -}}
 # test-ready.yaml
{{- if not .Values.daemonSet }}
apiVersion: v1
kind: Pod
metadata:
  name: "{{ include "ambassador.fullname" . }}-test-ready"
  labels:
    app.kubernetes.io/name: {{ include "ambassador.name" . }}
    helm.sh/chart: {{ include "ambassador.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
    {{- if .Values.extraLabels }}
      {{- toYaml .Values.extraLabels | nindent 4 }}
    {{- end }}
  annotations:
    "helm.sh/hook": test-success
spec:
  containers:
    - name: wget
      image: busybox
      command: ['wget']
      args:  ['{{ include "ambassador.fullname" . }}:{{ include "ambassador.servicePort" . }}/ambassador/v0/check_ready']
  restartPolicy: Never
{{- end }}

---
# Default values for ambassador.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.

replicaCount: 3
daemonSet: false

# Enable autoscaling using HorizontalPodAutoscaler
# daemonSet: true, autoscaling will be disabled
autoscaling:
  enabled: false
  minReplicas: 2
  maxReplicas: 5
  metrics:
    - type: Resource
      resource:
        name: cpu
        targetAverageUtilization: 60
    - type: Resource
      resource:
        name: memory
        targetAverageUtilization: 60

podDisruptionBudget: {}

# namespace:
  # name: default

# Additional container environment variable
env:
  {}
  # Exposing statistics via StatsD
  # STATSD_ENABLED: true
  # STATSD_HOST: statsd-sink
  # sets the minimum number of seconds between Envoy restarts
  # AMBASSADOR_RESTART_TIME: 15
  # sets the number of seconds that the Envoy will wait for open connections to drain on a restart
  # AMBASSADOR_DRAIN_TIME: 5
  # sets the number of seconds that Ambassador will wait for the old Envoy to clean up and exit on a restart
  # AMBASSADOR_SHUTDOWN_TIME: 10
  # labels Ambassador with an ID to allow for configuring multiple Ambassadors in a cluster
  # AMBASSADOR_ID: default

imagePullSecrets: []

securityContext:
  runAsUser: 8888

image:
  repository: quay.io/datawire/ambassador
  tag: 0.86.1
  pullPolicy: IfNotPresent

nameOverride: ""
fullnameOverride: ""
dnsPolicy: "ClusterFirst"
hostNetwork: false

service:
  type: LoadBalancer

  # Note that target http ports need to match your ambassador configurations service_port
  # https://www.getambassador.io/reference/modules/#the-ambassador-module
  ports:
    - name: http
      port: 80
      targetPort: 8080
      # protocol: TCP
      # nodePort: 30080
    - name: https
      port: 443
      targetPort: 8443
      # protocol: TCP
      # nodePort: 30443
    # TCPMapping_Port
      # port: 2222
      # targetPort: 2222
      # protocol: TCP
      # nodePort: 30222

  annotations:
  #############################################################################
  ## Ambassador should be configured using CRD definition. If you want
  ## to use annotations, the following is an example of annotating the
  ## Ambassador service with global configuration manifest.
  ##
  ## See https://www.getambassador.io/reference/core/ambassador and
  ## https://www.getambassador.io/reference/core/tls for more info
  #############################################################################
  #
  #  getambassador.io/config: |
  #    ---
  #    apiVersion: ambassador/v1
  #    kind: TLSContext
  #    name: ambassador
  #    secret: ambassador-certs
  #    hosts: ["*"]
  #    ---
  #    apiVersion: ambassador/v1
  #    kind: Module
  #    name: ambassador
  #    config:
  #      admin_port: 8001
  #      diag_port: 8877
  #      diagnostics:
  #        enabled: true
  #      enable_grpc_http11_bridge: false
  #      enable_grpc_web: false
  #      enable_http10: false
  #      enable_ipv4: true
  #      enable_ipv6: false
  #      liveness_probe:
  #        enabled: true
  #      lua_scripts:
  #      readiness_probe:
  #        enabled: true
  #      server_name: envoy
  #      service_port: 8080
  #      use_proxy_proto: false
  #      use_remote_address: true
  #      xff_num_trusted_hops: 0
  #      x_forwarded_proto_redirect: false
  #      load_balancer:
  #        policy: round_robin
  #      circuit_breakers:
  #        max_connections: 2048
  #      retry_policy:
  #        retry_on: "5xx"
  #      cors:

adminService:
  create: true
  type: ClusterIP
  port: 8877
  # NodePort used if type is NodePort
  # nodePort: 38877
  annotations:
    {}

rbac:
  # Specifies whether RBAC resources should be created
  create: true
  podSecurityPolicies:
    {}

scope:
  # tells Ambassador to only use resources in the namespace or namespace set by namespace.name
  singleNamespace: false

serviceAccount:
  # Specifies whether a service account should be created
  create: true
  # The name of the service account to use.
  # If not set and create is true, a name is generated using the fullname template
  name:

initContainers: []

sidecarContainers: []

livenessProbe:
  initialDelaySeconds: 30
  periodSeconds: 3
  failureThreshold: 3

readinessProbe:
  initialDelaySeconds: 30
  periodSeconds: 3
  failureThreshold: 3


volumes: []

volumeMounts: []

podLabels:
  {}

podAnnotations:
  {}
  # prometheus.io/scrape: "true"
  # prometheus.io/port: "9102"

deploymentAnnotations:
  {}
  # configmap.reloader.stakater.com/auto: "true"

resources:
  {}
  # If you do want to specify resources, uncomment the following
  # lines, adjust them as necessary, and remove the curly braces after 'resources:'.
  # limits:
  #  cpu: 100m
  #  memory: 128Mi
  # requests:
  #  cpu: 100m
  #  memory: 128Mi

priorityClassName: ""

nodeSelector: {}

tolerations: []

affinity: {}

ambassadorConfig: ""

crds:
  enabled: true
  create: true
  keep: true

pro:
  enabled: false
  image:
    repository: quay.io/datawire/ambassador_pro
    tag: 0.11.0
    # The tag for the image of your custom Ambassador Pro container.
    # Leave unset if not using a custom build of Ambassador Pro.
    # See https://www.getambassador.io/docs/guides/filter-dev-guide/
    customBuildTag:
  # As of Ambassador Pro 0.6.0, both the RateLimitService and AuthService use the same port
  ports:
    auth: 8500
    ratelimit: 8500
  logLevel: info
  # A license key is required to use Ambassador Pro.
  # Get a license key by signing up for a free trial here: https://www.getambassador.io/pro/free-trial
  licenseKey:
    value: "{{INSERT LICENSE KEY HERE}}"
    # The license key will be stored and read from a Kubernetes secret named ambassador-pro-license-key
    # Set create: true for the first install and create: false for all subsequent installs
    secret:
      enabled: true
      create: true
  # Ambassador Pro environment variables can be found at https://www.getambassador.io/reference/pro/environment
  # For consistency, AMBASSADOR_ID is copied over from the Ambassador env above and will be ignored if set here.
  env:
    {}
  resources: {}
  # If you want to specify resources, uncomment the following
  # lines and remove the curly braces after 'resources:'.
  # These are placeholder values and must be tuned.
  #   limits:
  #     cpu: 100m
  #     memory: 256Mi
  #   requests:
  #     cpu: 50m
  #     memory: 128Mi

  authService:
    enabled: true
    # Set additional configuration options. See https://www.getambassador.io/reference/services/auth-service for more information
    optional_configurations:
      # include_body:
      #   max_bytes: 4096
      #   allow_partial: true
      # status_on_error:
      #   code: 403
      # failure_mode_allow: false
      # retry_policy:
      #   retry_on: "5xx"
      #   num_retries: 2
      # add_linkerd_headers: true
      # timeout_ms: 30000

  rateLimit:
    enabled: true
    redis:
      # Annotations for Ambassador Pro's redis instance.
      annotations:
        deployment:
          {}
        service:
          {}
      resources: {}
      # If you want to specify resources, uncomment the following
      # lines and remove the curly braces after 'resources:'.
      # These are placeholder values and must be tuned.
      #   limits:
      #     cpu: 100m
      #     memory: 256Mi
      #   requests:
      #     cpu: 50m
      #     memory: 128Mi
  devPortal:
    enabled: false

# DEPRECATED: Ambassador now exposes the /metrics endpoint in Envoy.
# DEPRECATED: See https://www.getambassador.io/user-guide/monitoring#deployment for more information on how to use the /metrics endpoint
#
# DEPRECATED: Enabling the prometheus exporter creates a sidecar and configures ambassador to use it
prometheusExporter:
  enabled: false
  repository: prom/statsd-exporter
  tag: v0.8.1
  pullPolicy: IfNotPresent
  resources: {}
  # If you do want to specify resources, uncomment the following
  # lines, adjust them as necessary, and remove the curly braces after 'resources:'.
  #   limits:
  #     cpu: 100m
  #     memory: 256Mi
  #   requests:
  #     cpu: 50m
  #     memory: 128Mi
  # You can configure the statsd exporter to modify the behavior of mappings and other features.
  # See documentation: https://github.com/prometheus/statsd_exporter/tree/v0.8.1#metric-mapping-and-configuration
  # Uncomment the following line if you wish to specify a custom configuration:
  # configuration: |
  #   ---
  #   mappings:
  #   - match: 'envoy.cluster.*.upstream_cx_connect_ms'
  #     name: "envoy_cluster_upstream_cx_connect_time"
  #     timer_type: 'histogram'
  #     labels:
  #       cluster_name: "$1"
