Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to grep a yaml value

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)
like image 628
Jan Avatar asked Oct 19 '25 13:10

Jan


2 Answers

With awk:

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

Output:

10.244.1.9
like image 96
Cyrus Avatar answered Oct 22 '25 03:10

Cyrus


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
like image 30
tinita Avatar answered Oct 22 '25 03:10

tinita



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!