简体   繁体   English

如何使用 kubectl 命令从 k8s configmap 中的 yaml 文件中获取值?

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

Assume that the configmap is listed as follows:假设 configmap 如下所示:

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?如何使用kubectl命令从配置映射中获取keyB的值(即a-value )?

PS: I was thinking of using -o jsonpath or -o 'go-template=... options, but I couldn't figure out the correct syntax. PS:我正在考虑使用-o jsonpath-o 'go-template=...选项,但我无法弄清楚正确的语法。

You can get the data.my-config.yaml value either by using jsonpath or go-template .您可以使用jsonpathgo-template获取data.my-config.yaml值。

Example with jsonpath : jsonpath示例:

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

Example with go-template : 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 ).请注意,通过使用|-在您的 YAML 上,您定义了一个多行 YAML String ,这意味着返回的值是一个带有换行符的单个字符串( \n )。

If you want only the keyB value, you can use your output to feed a YAML processor like yq .如果您只需要keyB值,则可以使用 output 来为 YAML 处理器(如yq )提供数据。 Eg:例如:

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

Since this question is tagged jq, and since yq is just a wrapper around jq, here's one solution using yq alone:由于这个问题被标记为 jq,并且由于 yq 只是 jq 的包装,因此这里有一个单独使用 yq 的解决方案:

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/sed 组合,如下所示:

 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.这可以通过上面显示的第一次调用 yq 来完成,或者根本不使用 yq,尽管当然有很多警告 go 以及这种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM