how to access go templated kubernetes secret in manifest

5/12/2021

I'm running this tutorial https://www.elastic.co/guide/en/cloud-on-k8s/current/k8s-deploy-elasticsearch.html and found that the elasticsearch operator comes included with a pre-defined secret which is accessed through kubectl get secret quickstart-es-elastic-user -o go-template='{{.data.elastic | base64decode}}'. I was wondering how I can access it in a manifest file for a pod that will make use of this as an env var. The pod's manifest is as follows:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: user-depl
spec:
  replicas: 1
  selector:
    matchLabels:
      app: user
  template:
    metadata:
      labels:
        app: user
    spec:
      containers:
        - name: user
          image: reactor/user
          env:
            - name: PORT
              value: "3000"
            - name: ES_SECRET
              valueFrom:
                secretKeyRef:
                  name: quickstart-es-elastic-user
                  key: { { .data.elastic } }

---
apiVersion: v1
kind: Service
metadata:
  name: user-svc
spec:
  selector:
    app: user
  ports:
    - name: user
      protocol: TCP
      port: 3000
      targetPort: 3000

When trying to define ES_SECRET as I did in this manifest, I get this error message: invalid map key: map[interface {}]interface {}{\".data.elastic\":interface {}(nil)}\n. Any help on resolving this would be much appreciated.

-- reactor
elasticsearch
kubernetes

1 Answer

5/12/2021

The secret returned via API (kubectl get secret ...) is a JSON-structure, where there:

{
  "data": {
    "elastic": "base64 encoded string"
  }
}

So you just need to replace

key: { { .data.elastic } }

with

key: elastic

since it's secretKeyReference (e.g. you refer a value in some key in data (=contents) of some secret, which name you specified above). No need to worry about base64 decoding; Kubernetes does it for you.

-- anemyte
Source: StackOverflow