Search code examples
kubernetesjsonpath

Use JSONPATH to get configmap value


How can I retrieve a configmap value using jsonpath?

I'm trying to retrieve the value of haproxy.cfg from my configmap, but I can't get it just right:

kubectl get cm -l app=haproxy -o jsonpath="{['items'][0]['data']['haproxy.cfg']}"

The above returns no results. But I can definitely get the configmap if I leave off the haproxy.cfg:

kubectl get cm -l app=haproxy -o jsonpath="{['items'][0]['data']}"

Yields:

map[haproxy.cfg:
global
  user root
  group root
  maxconn 256
...
]

I can use jq:

kubectl get cm -l app=haproxy -o json | jq -r '.items[0].data["haproxy.cfg"]'

which yields exactly what I want:


global
  user root
  group root
  maxconn 256

If you need help creating your ConfigMap, here's the manifest for the one I am using:

apiVersion: v1
data:
    haproxy.cfg: "\nglobal\n  user root\n  group root\n  maxconn 256\n\n"
kind: ConfigMap
metadata:
    annotations:
      meta.helm.sh/release-name: haproxy
      meta.helm.sh/release-namespace: haproxy
    labels:
      app: haproxy
      app-version: 2.4.0
      app.kubernetes.io/managed-by: Helm
      heritage: Helm
      release: haproxy
      version: 0.0.3
    name: haproxy

Solution

  • Escape the . inside single quotes

    kubectl get cm -l app=haproxy -o jsonpath="{.items[0].data['haproxy\.cfg']}"
    

    * This didn't work a long time ago, pre 1.5. Then you needed to use go-template formatting.