# _helpers.tpl
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "kube2iam.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 "kube2iam.fullname" -}}
{{- $name := default .Chart.Name .Values.nameOverride -}}
{{- if ne $name .Release.Name -}}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s" $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}

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

{{/*
Return the proper Docker Image Registry Secret Names
*/}}
{{- define "kube2iam.imagePullSecrets" -}}
{{/*
Helm 2.11 supports the assignment of a value to a variable defined in a different scope,
but Helm 2.9 and 2.10 does not support it, so we need to implement this if-else logic.
Also, we can not use a single if because lazy evaluation is not an option
*/}}
{{- if .Values.global }}
{{- if .Values.global.imagePullSecrets }}
imagePullSecrets:
{{- range .Values.global.imagePullSecrets }}
  - name: {{ . }}
{{- end }}
{{- else if .Values.image.pullSecrets }}
imagePullSecrets:
{{- range .Values.image.pullSecrets }}
  - name: {{ . }}
{{- end }}
{{- end -}}
{{- else if .Values.image.pullSecrets }}
imagePullSecrets:
{{- range .Values.image.pullSecrets }}
  - name: {{ . }}
{{- end }}
{{- end -}}
{{- end -}} # clusterrole.yaml
{{- if .Values.rbac.create -}}
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  labels:
    app.kubernetes.io/name: {{ template "kube2iam.name" . }}
    helm.sh/chart: {{ template "kube2iam.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  name: {{ template "kube2iam.fullname" . }}
rules:
  - apiGroups:
      - ""
    resources:
      - namespaces
      - pods
    verbs:
      - list
      - watch
      - get
{{- if .Values.podSecurityPolicy.enabled }}
  - apiGroups:
      - policy
    resources:
      - podsecuritypolicies
    verbs:
      - use
    resourceNames:
      - {{ template "kube2iam.fullname" . }}
{{- end }}

{{- end -}}
 # clusterrolebinding.yaml
{{- if .Values.rbac.create -}}
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  labels:
    app.kubernetes.io/name: {{ template "kube2iam.name" . }}
    helm.sh/chart: {{ template "kube2iam.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  name: {{ template "kube2iam.fullname" . }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: {{ template "kube2iam.fullname" . }}
subjects:
  - kind: ServiceAccount
    name: {{ template "kube2iam.fullname" . }}
    namespace: {{ .Release.Namespace }}
{{- end -}}
 # daemonset.yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
  labels:
    app.kubernetes.io/name: {{ template "kube2iam.name" . }}
    helm.sh/chart: {{ template "kube2iam.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  name: {{ template "kube2iam.fullname" . }}
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ template "kube2iam.name" . }}
      app.kubernetes.io/instance: {{ .Release.Name }}
  template:
    metadata:
    {{- if .Values.podAnnotations }}
      annotations:
{{ toYaml .Values.podAnnotations | indent 8 }}
    {{- end }}
      labels:
        app.kubernetes.io/name: {{ template "kube2iam.name" . }}
        app.kubernetes.io/instance: {{ .Release.Name }}
      {{- if .Values.podLabels }}
{{ toYaml .Values.podLabels | indent 8 }}
      {{- end }}
    spec:
{{- include "kube2iam.imagePullSecrets" . | indent 6 }}
      containers:
        - name: kube2iam
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          imagePullPolicy: "{{ .Values.image.pullPolicy }}"
          args:
            - --host-interface={{ .Values.host.interface }}
            - --node=$(NODE_NAME)
          {{- if .Values.host.iptables }}
            - --host-ip={{ .Values.host.ip }}
          {{- end }}
            - --iptables={{ .Values.host.iptables }}
          {{- range $key, $value := .Values.extraArgs }}
            {{- if $value }}
            - --{{ $key }}={{ $value }}
            {{- else }}
            - --{{ $key }}
            {{- end }}
          {{- end }}
          {{- if .Values.verbose }}
            - --verbose
          {{- end }}
            - --app-port={{ .Values.host.port }}
          {{- if .Values.prometheus.metricsPort }}
            - --metrics-port={{ .Values.prometheus.metricsPort }}
          {{- else }}
            - --metrics-port={{ .Values.host.port }}
          {{- end }}
          env:
            - name: HOST_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.podIP
            - name: NODE_NAME
              valueFrom:
                fieldRef:
                  fieldPath: spec.nodeName
          {{- if or .Values.existingSecret (and .Values.aws.secret_key .Values.aws.access_key) }}
            - name: AWS_ACCESS_KEY_ID
              valueFrom:
                secretKeyRef:
                  name: {{ if .Values.existingSecret }}{{ .Values.existingSecret }}{{ else }}{{ template "kube2iam.fullname" . }}{{ end }}
                  key: aws_access_key_id
            - name: AWS_SECRET_ACCESS_KEY
              valueFrom:
                secretKeyRef:
                  name: {{ if .Values.existingSecret }}{{ .Values.existingSecret }}{{ else }}{{ template "kube2iam.fullname" . }}{{ end }}
                  key: aws_secret_access_key
          {{- end }}
          {{- if .Values.aws.region }}
            - name: AWS_DEFAULT_REGION
              value: {{ .Values.aws.region }}
          {{- end }}
          {{- range $name, $value := .Values.extraEnv }}
            - name: {{ $name }}
              value: {{ quote $value }}
          {{- end }}
          ports:
            - name: http
              containerPort: {{ .Values.host.port }}
            {{- if .Values.prometheus.metricsPort }}
            {{- if not (eq .Values.prometheus.metricsPort .Values.host.port) }}
            - name: metrics
              containerPort: {{ .Values.prometheus.metricsPort }}
            {{- end}}
            {{- end}}
        {{- if .Values.probe.enabled }}
          livenessProbe:
            httpGet:
              path: /healthz
              port: {{ .Values.host.port }}
              scheme: HTTP
            initialDelaySeconds: {{ .Values.probe.initialDelaySeconds }}
            periodSeconds: {{ .Values.probe.periodSeconds }}
            successThreshold: {{ .Values.probe.successThreshold }}
            failureThreshold: {{ .Values.probe.failureThreshold }}
            timeoutSeconds: {{ .Values.probe.timeoutSeconds }}
        {{- end }}
          resources:
{{ toYaml .Values.resources | indent 12 }}
        {{- if .Values.host.iptables }}
          securityContext:
            privileged: true
        {{- end }}
      hostNetwork: true
    {{- if .Values.nodeSelector }}
      nodeSelector:
{{ toYaml .Values.nodeSelector | indent 8 }}
    {{- end }}
    {{- if .Values.priorityClassName }}
      priorityClassName: {{ .Values.priorityClassName }}
    {{- end }}
    {{- if .Values.affinity }}
      affinity:
{{ toYaml .Values.affinity | indent 8 }}
    {{- end }}
      serviceAccountName: {{ if .Values.rbac.create }}{{ template "kube2iam.fullname" . }}{{ else }}"{{ .Values.rbac.serviceAccountName }}"{{ end }}
      tolerations:
{{ toYaml .Values.tolerations | indent 8 }}
{{- if semverCompare "^1.6-0" .Capabilities.KubeVersion.GitVersion }}
  updateStrategy:
    type: {{ .Values.updateStrategy }}
{{- end }}
 # podsecuritypolicy.yaml
{{- if .Values.podSecurityPolicy.enabled }}
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
  labels:
    app.kubernetes.io/name: {{ template "kube2iam.name" . }}
    helm.sh/chart: {{ template "kube2iam.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  name: {{ template "kube2iam.fullname" . }}
{{- if .Values.podSecurityPolicy.annotations }}
  annotations:
{{ toYaml .Values.podSecurityPolicy.annotations | indent 4 }}
{{- end }}
spec:
  privileged: true
  allowPrivilegeEscalation: true
  requiredDropCapabilities:
  - ALL
  hostNetwork: true
  hostPorts:
  - max: {{ .Values.host.port }}
    min: {{ .Values.host.port }}
{{- if .Values.prometheus.metricsPort }}
  - max: {{ .Values.prometheus.metricsPort }}
    min: {{ .Values.prometheus.metricsPort }}
{{- end }}
  hostIPC: false
  hostPID: false
  volumes:
  - 'configMap'
  - 'secret'
  - 'downwardAPI'
  runAsUser:
    rule: 'RunAsAny'    
  seLinux:
    rule: 'RunAsAny'
  supplementalGroups:
    rule: 'RunAsAny'
  fsGroup:
    rule: 'MustRunAs'
    ranges:
    - min: 1
      max: 65535
  readOnlyRootFilesystem: false
{{- end }}
 # secret.yaml
{{- if and .Values.aws.secret_key .Values.aws.access_key -}}
apiVersion: v1
kind: Secret
metadata:
  labels:
    app.kubernetes.io/name: {{ template "kube2iam.name" . }}
    helm.sh/chart: {{ template "kube2iam.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  name: {{ template "kube2iam.fullname" . }}
type: Opaque
data:
  aws_access_key_id: {{ .Values.aws.access_key | b64enc | quote }}
  aws_secret_access_key: {{ .Values.aws.secret_key | b64enc | quote }}
{{- end }}
 # service.yaml
{{- if or .Values.prometheus.serviceMonitor.enabled .Values.prometheus.service.enabled }}
apiVersion: v1
kind: Service
metadata:
  name: {{ template "kube2iam.fullname" . }}-metrics
  labels:
    app.kubernetes.io/name: {{ template "kube2iam.name" . }}
    helm.sh/chart: {{ template "kube2iam.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  {{- if .Values.prometheus.service.annotations }}
  annotations:
    {{- toYaml .Values.prometheus.service.annotations | nindent 4 }}
  {{- end }}
spec:
  selector:
    app.kubernetes.io/name: {{ template "kube2iam.name" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
  ports:
    {{- if .Values.prometheus.metricsPort }}
    - name: metrics
      port: {{ .Values.prometheus.metricsPort }}
      targetPort: {{ .Values.prometheus.metricsPort }}
    {{- else }}
    - name: http
      port: {{ .Values.host.port }}
      targetPort: {{ .Values.host.port }}
    {{- end }}
      protocol: TCP
{{ end }}
 # serviceaccount.yaml
{{- if .Values.rbac.create -}}
apiVersion: v1
kind: ServiceAccount
metadata:
  labels:
    app.kubernetes.io/name: {{ template "kube2iam.name" . }}
    helm.sh/chart: {{ template "kube2iam.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  name: {{ template "kube2iam.fullname" . }}
{{- end -}}
 # servicemonitor.yaml
{{- if .Values.prometheus.serviceMonitor.enabled }}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: {{ template "kube2iam.fullname" . }}
  {{- if .Values.prometheus.serviceMonitor.namespace }}
  namespace: {{ .Values.prometheus.serviceMonitor.namespace }}
  {{- end }}
  labels:
    app.kubernetes.io/name: {{ template "kube2iam.name" . }}
    helm.sh/chart: {{ template "kube2iam.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
    {{- if .Values.prometheus.serviceMonitor.labels }}
    {{- toYaml .Values.prometheus.serviceMonitor.labels | nindent 4 }}
    {{- end }}
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ template "kube2iam.name" . }}
      app.kubernetes.io/instance: {{ .Release.Name }}
  namespaceSelector:
    matchNames:
      - {{ .Release.Namespace }}
  endpoints:
    {{- if .Values.prometheus.metricsPort }}
    - port: metrics
    {{- else }}
    - port: http
    {{- end }}
      interval: {{ .Values.prometheus.serviceMonitor.interval }}
      path: /metrics
{{- end -}}

extraArgs: {}
#   base-role-arn: arn:aws:iam::0123456789:role/
#   default-role: kube2iam-default
#   api-server: ...
#   api-token: ...

extraEnv: {}
#    http_proxy: http://example.com:8080
#    NO_PROXY: localhost,127.0.0.1

host:
  ip: $(HOST_IP)
  iptables: false
  interface: docker0
  port: 8181

prometheus:
  # Port to expose the /metrics endpoint on. If unset, defaults to `host.port`
  # metricsPort: 9543

  service:
    enabled: false
#    annotations:
#      prometheus.io/scrape: "true"
#      prometheus.io/port: "9543"
#      prometheus.io/path: "/metrics"

  serviceMonitor:
    # Create prometheus-operator ServiceMonitor
    enabled: false
    # Interval at which the metrics endpoint is scraped
    interval: 10s
    # Alternative namespace to install the ServiceMonitor in
    namespace: ""
    # Labels to add to the service monitor
    labels: {}

image:
  repository: jtblin/kube2iam
  tag: 0.10.9
  pullPolicy: IfNotPresent
  ## Optionally specify an array of imagePullSecrets.
  ## Secrets must be manually created in the namespace.
  ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/
  ##
  # pullSecrets:
  #   - myRegistryKeySecretName

# AWS Access keys to inject as environment variables
aws:
  secret_key: ""
  access_key: ""
  region: ""

existingSecret: ""

## Node labels for pod assignment
## Ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
##
nodeSelector: {}

## Affinity configuration for pod assignment
## Ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
##
affinity: {}

## Annotations to be added to pods
##
podAnnotations: {}

priorityClassName: ""

podLabels: {}

probe:
  enabled: true
  initialDelaySeconds: 30
  periodSeconds: 5
  successThreshold: 1
  failureThreshold: 3
  timeoutSeconds: 1

rbac:
  ## If true, create & use RBAC resources
  ##
  create: false

  ## Ignored if rbac.create is true
  ##
  serviceAccountName: default

resources: {}
  # limits:
  #   cpu: 4m
  #   memory: 16Mi
  # requests:
  #   cpu: 4m
  #   memory: 16Mi

## Strategy for DaemonSet updates (requires Kubernetes 1.6+)
## Ref: https://kubernetes.io/docs/tasks/manage-daemon/update-daemon-set/
##
updateStrategy: OnDelete

verbose: false

tolerations: []

podSecurityPolicy:
  ## if true, a podSecurityPolicy object will be created. rbac.create has to be set to true to also create RBAC roles and bindings for the podSecurityPolicy.
  enabled: false

  ## annotations to add to the podSecurityPolicy object
  annotations: {}
