How to grep a yaml value

5/12/2018

I try to get a value from a YAML file within a shell:

apiVersion: v1
items:
- apiVersion: v1
  kind: Pod
  spec:
    containers:
    hostIP: 12.198.110.192
    phase: Running
    podIP: 10.244.1.9

With kubectl get pods -l run=hello-kube -o yaml | grep podIP: I get this ouput:

    podIP: 10.244.1.9

My goal is to save that value in a Environment Variable, but I only get the key/value-pair:

export PODIP=$(kubectl get pods -l run=hello-kube -o yaml | grep podIP)
-- Jan
grep
kubernetes
shell
yaml

3 Answers

5/12/2018

With awk:

kubectl get pods -l run=hello-kube -o yaml | awk '/podIP:/ {print $2}'

Output:

10.244.1.9

-- Cyrus
Source: StackOverflow

5/13/2018

You can also use yq (https://github.com/mikefarah/yq), which is a tool similar to jq.

Then do:

% yq read file.yaml items.0.spec.podIP
10.244.1.9
-- tinita
Source: StackOverflow

5/13/2018

You may also use the format json to get the value with jsonpath, something like,

kubectl get pods -l app=cron -o=jsonpath='{.items[0].status.podIP}'

Thanks

-- qingdaojunzuo
Source: StackOverflow