Search code examples
kubernetesjsonpathconfigmap

Retrieve information from a configmap using jsonpath


I have the following configmap where I want to retrieve the IPs using jsonpath how can that be done?

apiVersion: v1
data:
  domain.yaml: |
    dns:
      - 127.0.0.1
      - 127.0.0.2

I have tried the following which does not work: kubectl get cm domain -o jsonpath={.domain.yaml.dns[0]}


Solution

  • this is not quite simple, as the

    dns:
    - 127.0.0.1
    - 127.0.0.2
    

    is interpreted as a single json value.

    for example kubectl get cm testcm -o jsonpath='{.data}' returns the following output {"domain.yaml":"dns:\n - 127.0.0.1\n - 127.0.0.2\n"} as you can see it has "domain.yaml" as key, and the rest is a simple string value.

    in order to get the ips, we can use jq and cut magic. For example

    kubectl get cm testcm -o jsonpath='{.data.*}' | cut -d$'\n' -f2 | sed 's/  - //g' 
    

    would return 127.0.0.1