Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Specifically, how can I extract the 192.168.0.0/16 value of the CALICO_IPV4POOL_CIDR variable into a bash variable?

        - name: CALICO_IPV4POOL_CIDR
          value: "192.168.0.0/16"

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.

like image 896
CodeMed Avatar asked Mar 01 '19 00:03

CodeMed


2 Answers

As others are commenting, it is recommended to make use of yq (along with jq) if available.
Then please try the following:

value=$(yq -r 'recurse | select(.name? == "CALICO_IPV4POOL_CIDR") | .value' "calico.yaml")
echo "$value"

Output:

192.168.0.0/16
like image 73
tshiono Avatar answered Oct 19 '22 03:10

tshiono


If you're able to install new dependencies, and are planning on dealing with lots of yaml files, yq is a wrapper around jq that can handle yaml. It'd allow a safe (non-grep) way of accessing nested yaml values.

Usage would look something like MY_VALUE=$(yq '.myValue.nested.value' < config-file.yaml)

Alternatively, How can I parse a YAML file from a Linux shell script? has a bash-only parser that you could use to get your value.

like image 45
willis Avatar answered Oct 19 '22 03:10

willis