kubernetes pod name to be used as argument

1/8/2019

I want to use the Kubernetes pod name to be used as an identifier in my container as an argument.

I have deployed my echo containers on my Kubernetes cluster using the following config:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: echo1
spec:
  selector:
    matchLabels:
      app: echo1
  replicas: 2
  template:
    metadata:
      labels:
        app: echo1
    spec:
      containers:
      - name: echo1
        image: hashicorp/http-echo
        args:
        - "-text=echo1"
        ports:
        - containerPort: 5678

When I do "kubectl get pods":

NAME                                     READY   STATUS    RESTARTS   AGE
echo1-76c689b7d-48h4v                    1/1     Running   0          19h
echo1-76c689b7d-4gq2v                    1/1     Running   0          19h

I want to echo the pod name by passing the pod name in my config above:

args:
            - "-text=echo1"

How do I access my pod name to be used in my args?

-- Sonam
kubernetes

1 Answer

1/8/2019

So a few things. First you would use the fieldRef syntax for an environment variable as shown in https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information/. Then you would use the env var in your argument ("-text=$(PODNAME)"). However this will give you the actual pod name, like echo1-76c689b7d-48h4v. What you want is either the deployment name or the value of the app label, the latter is easier to instead of metadata.name as the field path, use something like metadata.labels['app'] (requires Kubernetes 1.9+).

-- coderanger
Source: StackOverflow