How to use kubectl command to get a value from a yaml file inside a k8s configmap?

10/17/2019

Assume that the configmap is listed as follows:

apiVersion: v1
kind: ConfigMap
metadata:
  name: my-configmap
  namespace: ${namespace}
data:
  my-config.yaml: |-
    keyA:
      keyB: a-value

How can I get the value of keyB (which is a-value) from the configmap using the kubectl command?

PS: I was thinking of using -o jsonpath or -o 'go-template=... options, but I couldn't figure out the correct syntax.

-- injoy
go-templates
jq
jsonpath
kubernetes

2 Answers

10/17/2019

You can get the data.my-config.yaml value either by using jsonpath or go-template.

Example with jsonpath:

$ kubectl get cm my-configmap -o "jsonpath={.data['my-config\.yaml']}"
keyA:
  keyB: a-value

Example with go-template:

$ kubectl get cm my-configmap -o 'go-template={{index .data "my-config.yaml"}}'
keyA:
  keyB: a-value

Note that by using |- on your YAML, you are defining a Multiline YAML String, which means that the returned value is a single string with line breaks on it (\n).

If you want only the keyB value, you can use your output to feed a YAML processor like yq. E.g:

$ kubectl get cm my-configmap -o 'go-template={{index .data "my-config.yaml"}}' | yq -r .keyA.keyB
a-value
-- Eduardo Baitello
Source: StackOverflow

10/17/2019

Since this question is tagged jq, and since yq is just a wrapper around jq, here's one solution using yq alone:

yq -r '.data."my-config.yaml"' configmap.yml |
  yq .keyA.keyB

Of course, it might be just as well to use a grep/sed combination along the lines of:

 grep keyB: | sed 's/.*keyB: *//'

This could be done with the first invocation of yq shown above, or without using yq at all, though of course there are many caveats that go along with such an approach.

-- peak
Source: StackOverflow