Monday, February 21, 2022

[SOLVED] how get text value of name option in k8s yaml file

Issue

I have many k8s deployment files with yaml format.

I need to get the value of the first occurrence of name option only inside these files.

Example of deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80

I need to get only the value nginx-deployment

I tried, but no success:

grep 'name: ' ./deployment.yaml | sed -n -e 's/name: /\1/p'

Solution

With sed. Find first row with name, remove everything before : and : and then quit sed.

sed -n '/name/{ s/.*: //; p; q}' deployment.yaml

Output:

nginx-deployment


Answered By - Cyrus
Answer Checked By - Terry (WPSolving Volunteer)