kubectl exec into a container without using the random guid at the end of the pod name - kubernetes

To exec into a container in a pod, I use the following two commands (note the template flag in the first command trims the output to print just the name of the pods):
$ kubectl get pods --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'
app-api-6421cdf4fd-x9tbk
app-worker-432f86f54-fknxw
app-frontend-87dd65d49c-6b4mn
app-rabbit-413632c874-s2ptw
$ kubectl exec -it app-api-6421cdf4fd-x9tbk -- bash
It would be nice to exec into the container without having to discover the random guid at the end of the pod name every single time. How can I do this?

You can exec into a pod using the deployment
You can use the following command:
kubectl exec -it deploy/<deployment-name> -- bash

Suppose you have a Deployment with the name myadmin and namespace demo. After deploy, you can exec into the deployment's pod by running the below command:
$ export id=( kubectl get pod -n demo | grep 'myadmin' | awk 'END {print $1}' | xargs echo) && kubectl -n demo exec -it $id -- bash

I believe you expect this.
(sed 's/pod\///' is used below because kubectl get pod -o name gives you names like pod/rabbitmq-0 and you should cut first part)
kubectl exec -it $(kubectl get pod -o name | sed 's/pod\///' | grep api) -- bash
Similar to previous one you can use any known commands to find and sort needed objects. Providing version from your initial question
kubectl exec -it $(kubectl get pod --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'| grep api) -- bash

Related

Understanding kubectl run command

I am tryng to create a pod using kubectl run by creating an yaml file, where first command is creating container but showing state as error and second one is creating with out any issue. what is the difference between these commands?
master $ kubectl run --restart=Never --image=busybox static-busybox --command -- sleep 1000 --dry-run -o yaml //Error container
master $ kubectl run --restart=Never --image=busybox static-busybox --dry-run -o yaml --command -- sleep 1000 //working command
In the first one parameters --dry-run -o yaml are applied to the command you run in the container (sleep), in the second one, they are applied to your kubectl execution
As per the syntax of the kubectl run command needs to be at the end. That's precisely the reason why first command is not working but second one is working.
Usage:
kubectl run NAME --image=image [--env="key=value"] [--port=port] [--dry-run=server|client] [--overrides=inline-json]
[--command] -- [COMMAND] [args...] [options]

How to access a kubernetes pod by its partial name?

I often run tasks like:
Read the log of the service X
or
Attach a shell inside the service Y
I always use something in my history like:
kubectl logs `kubectl get pods --no-headers -o custom-columns=":metadata.name" | grep <partial_name>`
or
kubectl exec -it `kubectl get pods --no-headers -o custom-columns=":metadata.name" | grep <partial_name>` bash
Do you know if kubectl has already something in place for this? Or should I create my own set of aliases?
Kubernetes instances are loosely coupled by the means of labels (key-value pairs). Because of that Kubernetes provides various functionalities that can help you to operate on sets of objects based on labels.
In case you have several pods of the same service good chances that they are managed by some ReplicaSet with the use of some specific label. You should see it if you run:
kubectl get pods --show-labels
Now for aggregating logs for instance you could use label selector like:
kubectl logs -l key=value
For more info please see: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ .
added to my .zshconfig
sshpod () {
kubectl exec --stdin --tty `kubectl get pods --no-headers -o custom-columns=":metadata.name" | grep ${1} | head -n 1` -- /bin/bash
}
usage
sshpod podname
this
finds all pods
greps needed name
picks the first
sshs into the pod
You can go access a pod by its deployment/service/etc:
kubectl exec -it svc/foo -- bash
kubectl exec -it deployment/bar -- bash
Kubernetes will pick a pod that matches the criteria and send you to it.
You can enable shell autocompletion. Kubectl provides this support for Bash and Zsh which will save you a lot of typing (you will use TAB to get the suggestion/completion).
Kuberentes documentations has a great set of information about how to enable autocompletion under Optional kubectl configurations. It covers Bash on Linux, Bash on MacOS and Zsh.

Do we have command to execute multiple arguments in kubernetes

I have a pod running in kubernetes and i need to run two commands in one line.
Say,
kubectl exec -it <pod name> -n <namespace > -- bash -c redis-cli
above command will open redis-cli
i want to run one more command after exec in one line ie info, i am trying below which is not working:
kubectl exec -it <pod name> -n <namespace > -- bash -c redis-cli -- info
You have to put your command and all the parameters between apostrophes.
in your example it would be:
kubectl exec -it <pod_name> -n <namespace> -- bash -c 'redis-cli info'
From Bash manual: bash -c: If the -c option is present, then commands are read from the first non-option argument commaqnd_string.
Other option (which in my opinion is a better approach) is to get the output from the command with an instant pod, which creates, runs and deletes the pod right after that, like this:
kubectl run --namespace <YOUR_NAMESPACE> <TEMP_RANDOM_POD_NAME> --rm --tty -i --restart='Never' --env REDIS_PASSWORD=$REDIS_PASSWORD --image docker.io/bitnami/redis:5.0.7-debian-10-r0 -- bash -c 'redis-cli -h redis-master -a $REDIS_PASSWORD info'
in my case the password was stored in a envvar called $REDIS_PASSWORD and I'm connecting to a server in a pod called redis-master.
I let it as I runned it to show that you can use as much parameters as needed.
POC:
user#minikube:~$ kubectl run --namespace default redis-1580466120-client --rm --tty -i --restart='Never' --env REDIS_PASSWORD=$REDIS_PASSWORD --image docker.io/bitnami/redis:5.0.7-debian-10-r0 -- bash -c 'redis-cli -h redis-master -a $REDIS_PASSWORD info'
10:41:10.65
10:41:10.66 Welcome to the Bitnami redis container
10:41:10.66 Subscribe to project updates by watching https://github.com/bitnami/bitnami-docker-redis
10:41:10.66 Submit issues and feature requests at https://github.com/bitnami/bitnami-docker-redis/issues
10:41:10.67 Send us your feedback at containers#bitnami.com
10:41:10.67
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
# Server
redis_version:5.0.7
redis_git_sha1:00000000
redis_git_dirty:0
...
{{{suppressed output}}}
...
# CPU
used_cpu_sys:1.622434
used_cpu_user:1.313600
used_cpu_sys_children:0.013942
used_cpu_user_children:0.008014
# Cluster
cluster_enabled:0
# Keyspace
pod "redis-1580466120-client" deleted
Not get your question, do you want to get the information from redis-cli?
kubernetes exec -it <pod name> -n <namespace > -- bash -c 'redis-cli info'
Did you try to link your commands using && ?
kubernetes exec -it <pod name> -n <namespace > -- bash -c redis-cli && info

How do I get a single pod name for kubernetes?

I'm looking for a command like "gcloud config get-value project" that retrieves a project's name, but for a pod (it can retrieve any pod name that is running). I know you can get multiple pods with "kubectl get pods", but I would just like one pod name as the result.
I'm having to do this all the time:
kubectl get pods # add one of the pod names in next line
kubectl logs -f some-pod-frontend-3931629792-g589c some-app
I'm thinking along the lines of "gcloud config get-value pod". Is there a command to do that correctly?
There are many ways, here are some examples of solutions:
kubectl get pods -o name --no-headers=true
kubectl get pods -o=name --all-namespaces | grep kube-proxy
kubectl get pods -o go-template --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'
For additional reading, please take a look to these links:
kubernetes list all running pods name
Kubernetes list all container id
https://kubernetes.io/docs/tasks/access-application-cluster/list-all-running-container-images/
You can use the grep command to filter any output on stdout. So to get pods matching a specified pattern you can use a command like this:
> kubectl get pods --all-namespaces|grep grafana
Output:
monitoring kube-prometheus-grafana-57d5b4d79f-smkz6 2/2 Running 0 1h
To only output the pod name, you can use the awk command with a parameter of '{print $2}', which displays the second column of the previous output:
kubectl get pods --all-namespaces|grep grafana|awk '{print $2}'
To only display one line you can use the head command like so:
kubectl get pods --all-namespaces|grep grafana|awk '{print $2}'|head -n 1
This will output the last pod name :
kubectl get pods -o go-template --template ' {{range .items}}{{.metadata.name}}{{"\n"}}{{end}}' | awk '{print $1}' | tail -n 1
if you want to fetch logs for a pod:
kubectl logs -f kubectl get pods -o go-template --template ' {{range .items}}{{.metadata.name}}{{"\n"}}{{end}}' | awk '{print $1}' | tail -n 1
just run the command with a single quotes.
Links:
kubernetes list all running pods name
https://kubernetes.io/docs/tasks/access-application-cluster/list-all-running-container-images/
Hope this helps!!

kubernetes list all running pods name

I looking for the option to list all pods name
How to do without awk (or cut). Now i'm using this command
kubectl get --no-headers=true pods -o name | awk -F "/" '{print $2}'
Personally I prefer this method because it relies only on kubectl, is not very verbose and we don't get the pod/ prefix in the output:
kubectl get pods --no-headers -o custom-columns=":metadata.name"
You can use the go templating option built into kubectl to format the output to just show the names for each pod:
kubectl get pods --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'
Get Names of pods using -o=name Refer this cheatsheet for more.
kubectl get pods -o=name
Example output:
pod/kube-xyz-53kg5
pod/kube-xyz-jh7d2
pod/kube-xyz-subt9
To remove trailing pod/ you can use standard bash sed command
kubectl get pods -o=name | sed "s/^.\{4\}//"
Example output:
kube-xyz-53kg5
kube-pqr-jh7d2
kube-abc-s2bt9
To get podname with particular string, standard linux grep command
kubectl get pods -o=name | grep kube-pqr | sed "s/^.\{4\}//"
Example output:
kube-pqr-jh7d2
With this name, you can do things, like adding alias to get shell to running container:
alias bashkubepqr='kubectl exec -it $(kubectl get pods -o=name | grep kube-pqr | sed "s/^.\{4\}//") bash'
You can use custom-columns in output option to get the name and --no-headers option
kubectl get --no-headers=true pods -l app=external-dns -o custom-columns=:metadata.name
You can use -o=name to display only pod names. For example to list proxy pods you can use:
kubectl get pods -o=name --all-namespaces | grep kube-proxy
The result is:
pod/kube-proxy-95rlj
pod/kube-proxy-bm77b
pod/kube-proxy-clc25
There is also this solution:
kubectl get pods -o jsonpath={..metadata.name}
Here is another way to do it:
kubectl get pods -o=name --field-selector=status.phase=Running
The --field-selector=status.phase=Running is needed as the question mention all the running pod names. If the all in the question is for all the namespaces, just add the --all-namespaces option.
Note that this command is very convenient when one want a quick way to access something from the running pod(s), such as logs :
kubectl logs -f $(kubectl get pods -o=name --field-selector=status.phase=Running)
Get all running pods in the namespace
kubectl get pods --field-selector=status.phase=Running --no-headers -o custom-columns=":metadata.name"
From viewing, finding resources.
You could also specify namespace with -n <namespace name>.
jsonpath alternative
kubectl get po -o jsonpath="{range .items[*]}{#.metadata.name}{end}" -l app=nginx-ingress,component=controller
see also:
more examples of kubectl output options
If you want to extract specific container's pod name then
A simple command can do all the hard work
kubectl get pods --template '{{range .items}}{{.metadata.name}}{{end}}' --selector=app=<CONTAINER-NAME>
Just replace <CONTAINER-NAME> with your service container-name
Well, In our case we have kept pods inside different namespace, here to identify the specific pod or list of pods we ran following command-
Approach 1:
To get the list of namespaces
kubectl get ns -A
To get all the pods inside one namespaces kubectl get pods -n <namespace>
Approach 2:
Use this command-
kubectl get pods --all-namespaces
kubectl exec -it $(kubectl get pods | grep mess | awk '{print $1}') /bin/bash
kubectl get po --all-namespaces | awk '{if ($4 != "Running") system ("kubectl -n " $1 " delete pods " $2 " --grace-period=0 " " --force ")}'