Mohit Sharma
Mohit Sharma

Reputation: 31

How do I print the metadata.labels information in go template in Kubernetes?

How do I print the metadata label information from the Kubernetes Pod?

Given, this is the pod configuration

apiVersion: v1
kind: Pod
metadata:
  annotations:
    kubernetes.io/psp: eks.privileged
  creationTimestamp: "2022-10-13T01:43:06Z"
  generateName: my-service-1-84bc99cfb5-
  labels:
    app.kubernetes.io/instance: my-service-1
    app.kubernetes.io/name: my-service
  name: my-service-1-84bc99cfb5-sx7vm
  namespace: my-service
 spec:
  containers:
     ...

When I am running the below command

kubectl get pods -n my-service -o go-template --template '{{range .items}}{{.metadata.name}} {{.metadata.namespace}} {{.metadata.creationTimestamp}} {{.metadata.labels}} {{"\n"}}{{end}}'

its returns this output

my-service-1-84bc99cfb5-sx7vm my-service 2022-10-13T01:43:06Z map[app.kubernetes.io/instance:my-service-1 app.kubernetes.io/name:my-service]

but I want to have

my-service-1-84bc99cfb5-sx7vm my-service 2022-10-13T01:43:06Z my-service-1

Upvotes: 0

Views: 1428

Answers (1)

Adiii
Adiii

Reputation: 60076

you can use the index function

However, this kind of access is limited to keys which are strings and contain only characters in the set (a-z,A-Z,_,1-9), and which do not begin with a number. If the key doesn’t conform to these rules, you can use the index function (like how arrays are accessed): {{ index $map "foo-bar" }}

so we can use {{index .metadata.labels "app.kubernetes.io/name"}}

 kubectl get pods  -n my-service -o go-template --template '{{range .items}}{{.metadata.name}} {{.metadata.namespace}} {{.metadata.creationTimestamp}} {{index .metadata.labels "app.kubernetes.io/name" -}} {{"\n"}}{{end}}'

output

datadog-zxmtd datadog 2022-10-09T08:20:50Z datadog

Upvotes: 2

Related Questions