从bash中的YAML文件解析一个嵌套变量 [英] Parse a nested variable from YAML file in bash
问题描述
来自
A complex .yaml
file from this link needs to be fed into a bash script that runs as part of an automation program running on an EC2 instance of Amazon Linux 2. Note that the .yaml
file in the link above contains many objects, and that I need to extract one of the environment variables defined inside one of the many objects that are defined in the file.
具体来说,如何将
CALICO_IPV4POOL_CIDR
变量的192.168.0.0/16
值提取到bash变量中?
Specifically, how can I extract the
192.168.0.0/16
value of theCALICO_IPV4POOL_CIDR
variable into a bash variable?
- name: CALICO_IPV4POOL_CIDR
value: "192.168.0.0/16"
我已经阅读了很多其他的文章和博客文章,这些文章和文章分析更平坦,更简单的.yaml
文件,但是在这些问题中,没有其他示例显示如何提取嵌套值(如CALICO_IPV4POOL_CIDR
的value
).
I have read a lot of other postings and blog entries about parsing flatter, simpler .yaml
files, but none of those other examples show how to extract a nested value like the value
of CALICO_IPV4POOL_CIDR
in this question.
推荐答案
MYVAR=$(\
curl https://docs.projectcalico.org/v3.3/getting-started/kubernetes/installation/hosted/kubernetes-datastore/calico-networking/1.7/calico.yaml | \
grep -A 1 CALICO_IPV4POOL_CIDR | \
grep value | \
cut -d ':' -f2 | \
tr -d ' "')
用您替换的文件替换curl https://docs.projectcalico.org/v3.3/getting-started/kubernetes/installation/hosted/kubernetes-datastore/calico-networking/1.7/calico.yaml
.这将通过管道传递到grep -A 1 CALICO_IPV4POOL_CIDR
.这将为您提供两行文本:名称行和值行.这将通过管道传递到grep value
,这现在为我们提供了我们想要的仅包含值的行.这将通过管道传递到cut -d ':' -f2
,后者使用冒号作为分隔符,并为我们提供第二个字段. $(...)
执行附带的脚本,并将其分配给MYVAR
.在此脚本之后,echo $MYVAR
应该生成192.168.0.0/16
.
Replace curl https://docs.projectcalico.org/v3.3/getting-started/kubernetes/installation/hosted/kubernetes-datastore/calico-networking/1.7/calico.yaml
with however you're sourcing the file. That gets piped to grep -A 1 CALICO_IPV4POOL_CIDR
. This gives you 2 lines of text: the name line, and the value line. That gets piped to grep value
, which now gives us the line we want with just the value. That gets piped to cut -d ':' -f2
which uses the colon as a delimiter and gives us the second field. $(...)
executes the enclosed script, and it is assigned to MYVAR
. After this script, echo $MYVAR
should produce 192.168.0.0/16
.
这篇关于从bash中的YAML文件解析一个嵌套变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!