首页 > 解决方案 > 从 yaml 文件中的变量中提取 yaml 文件

问题描述

我有一个简单的 yaml 文件:

# replicas: number of pods
replicas: 1
# test
hello: world

我将其存储在 kubernetes 配置映射中:

apiVersion: v1
data:
  helm_values: |
    # replicas: number of pods
    replicas: 1
    # test
    hello: world
kind: ConfigMap
metadata:
  creationTimestamp: 2018-07-30T06:07:38Z

我现在想从 configmap 中提取内部 yaml 文件。尝试yq我得到:

$ VAR=$(oc get configmap backoffice-deployer -o yaml | yq .data.helm_values)
$ echo $VAR
"# replicas: number of pods\nreplicas: 1\n# test\nhello: world\n"

如果我尝试将 VAR 回显或打印到文件中,则它的格式不像原始文件那样好。

在 bash 中以原始文件格式获取提取的数据的最简单方法是什么?

标签: bashyamlyq

解决方案


我无法完全复制您的代码,但这就是我得到的(OSX,bash v4.4.23,yq v2.1.0):

var=$(cat test.yaml | yq r - data.helm_values)
echo "$var"

带输出

# replicas: number of pods
replicas: 1
# test
hello: world

如果我忘记了引号 ( echo $var),那么:

# replicas: number of pods replicas: 1 # test hello: world

(没有换行符,没有\n)。

我什至可以进一步处理它:

echo "$var" | yq r - hello
# => world

使用 yq v2.6.0 命令参数已更改:

var=$(cat test.yaml | yq -r .data.helm_values)
echo "$var"

推荐阅读