shortcut for typing kubectl --all-namespaces everytime - bash

Is there any alias we can make for all-namespace as kubectl don't recognise the command kubectl --all-namespaces or any kind of shortcut to minimize the typing of the whole command.

New in kubectl v1.14, you can use -A instead of --all-namespaces, eg:
kubectl get -A pod
(rejoice)

Is there any alias we can make for all-namespace
Based on this excellent SO answer you can create alias that inserts arguments between prefix and suffix like so:
alias kca='f(){ kubectl "$#" --all-namespaces -o wide; unset -f f; }; f'
and then use it regularly like so:
kca get nodes
kca get pods
kca get svc,sts,deploy,pvc,pv
etc..
Note: There is -o wide added for fun as well to get more detailed info about resources not normally namespaced like nodes and pv...

Related

kubernetes redis-cluster pod by pod login using shell script?

Currently, I am trying to prepare a shell script for redis-cluster backup of each pod running in a particular namespace.
I wanted to achieve it by performing two operations:
login to each pod one by one and then connect to redis-cli and execute BGSAVE command.
take a copy of dump.rdb file from each pod and place it at backup folder.
for first part, I have prepared following code snippet:
#!/bin/bash
NS=$1
for i in `cat "$NS"_POD_LIST`;
do
echo "POD: $i";
kubectl exec -it $i -n $NS -- bash -c "redis-cli -c BGSAVE"
##After BGSAVE wanted to get out of redis-cli, but it get stuck here, unable to switch to other pod
done
now on the second part wanted to copy dump.rdb file from each pod to the destination folder, but this execution will be outside of pod..
SOURCE_DIR="/redis/data"
BACKUP_DIR="/pod/backup"
for i in `cat "$NS"_POD_LIST`;
do
echo "POD: $i";
kubectl cp $NS/$i:$SOURCE_DIR $BACKUP_DIR
done
Please let me know on this code snippet how to achieve this?

Executing a kubernetes pod with the use of pod name

I am writing a shell script for executing a pod for which the syntax is:
winpty kubectl --kubeconfig="C:\kubeconfig" -n namespace exec -it podname bash
This works fine but since podname is not stable and changes for every deployment so is there any alternative for this?
Thanks.
You can use normally $ kubectl exec command but define value for changing pod name.
Assuming that you have deployment and labeled pods: app=example, simply execute:
$ kubectl exec -it $(kubectl get pods -l app=example -o custom-columns=:metadata.name) -- bash
EDIT:
You can also execute:
POD_NAME = $(kubectl get pods -l app=example -o custom-columns=":metadata.name")
or
POD_NAME = $(kubectl get pods -l app=example -o jsonpath = "{. Items [0] .metadata.name}")
finally
$ winpty kubectl exec -ti $POD_NAME --bash
Make sure that you execute command in proper namespace - you can also add -n flag and define it.
You can use the following command:
kubectl -n <namespace> exec -it deploy/<deployment-name> -- bash
Add a service to your application:
As you know, pods are ephemeral; They come in and out of existence dynamically to ensure your application stays in compliance with your configuration. This behavior implements the scaling and self-healing aspects of kubernetes.
You application will consist of one or more pods that are accessible through a service , The application's service name and address does not change and so acts as the stable interface to reach your application.
This method works both if your application has one pod or many pods.
Does that help?

Grep command to extract a kubernetes pod name

I am currently working on a bash script to reduce the time it takes for me to build the db for a project.
Currently I have several databases running in the same namespace and I want to extract only the specific pod name.
I run kubectl get pods
NAME READY STATUS RESTARTS AGE
elastic 1/1 Running 0 37h
mysql 1/1 Running 0 37h
Now I want to save one of the pod names.
I'm currently running this foo=$(kubectl get pods | grep -e "mysql")
and it returns mysql 1/1 Running 0 37h which is the expected results of the command. Now I just want to be able to extract the pod name as that variable so that I can pass it on at a later time.
This should work for you
foo=$(kubectl get pods | awk '{print $1}' | grep -e "mysql")
kubectl already allows you to extract only the names:
kubectl get pods -o=jsonpath='{range .items..metadata}{.name}{"\n"}{end}' | fgrep mysql
If I'm not mistaken, you merely needs to get only pod names to reuse these later.
The kubectl get --help provides a lot of good information on what you can achieve with just a kubectl without invoking the rest of the heavy artillery like awk, sed, etc.
List a single pod in JSON output format.
kubectl get -o json pod web-pod-13je7
List resource information in custom columns.
kubectl get pod test-pod -o
custom-columns=CONTAINER:.spec.containers[0].name,IMAGE:.spec.containers[0].image
Return only the phase value of the specified pod.
kubectl get -o template pod/web-pod-13je7 --template={{.status.phase}}
In this particular case I see at least 2 workarounds :
1) Custom columns. You can get virtually any output (and then you can grep/tr/awk if needed):
$ kubectl get pods --no-headers=true -o custom-columns=NAME_OF_MY_POD:.metadata.name
mmmysql-6fff9ffdbb-58x4b
mmmysql-6fff9ffdbb-72fj8
mmmysql-6fff9ffdbb-p76hx
mysql-tier2-86dbb787d9-r98qw
nginx-65f88748fd-s8mgc
2) jsonpath (the one #vault provided):
kubectl get pods -o=jsonpath='{.items..metadata.name}'
Hope that sheds light on options you have to choose from.
Let us know if that helps.
kubectl get pods | grep YOUR_POD_STARTING_NAME
For Example
kubectl get pods | grep mysql

Bash selection menu based on command output

How can I make a selection menu based on other command output?
For example running following command:
kubectl config get-contexts
I am getting following output:
CURRENT NAME CLUSTER AUTHINFO NAMESPACE
* Name1 Cluster1 Auth1
Name2 Cluster2 Auth3
Name3 Cluster3 Auth3
What I'd like to achieve is to print NAME and CLUSTER columns as a menu options and if any is selected pass it as variable to another command:
kubectl config use context $NameX
But have no idea how to do this with command output.
In order to use the output of a command as input to another one, you might use backticks or, more readable, $() (but the latter does not always work).
For example, give some more information on the ls "program":
which ls
file /bin/ls
This can be shortened to:
file $(which ls)
or:
file `which ls`
In your example, it will be something like:
kubectl config use context $(kubectl config get-contexts ...), or:
kubectl config use context `kubectl config get-contexts ...`
Obviously you'll need to specify exactly which information you need from the config in order for this to work.

How to get the running pod name when there are other pods terminating?

I am using kubernetes cluster to run dev environments for myself and other developers. I have written a few shell functions to help everyone deal with their pods without typing long kubectl commands by hand. For example, to get a prompt on one of the pods, my functions use the following
kubectl exec -it $(kubectl get pods --selector=run=${service} --field-selector=status.phase=Running -o jsonpath="{.items[*].metadata.name}") -- bash;
where $service is set to a service label I want to access, like postgres or redis or uwsgi.
Since these are development environments there is always one of each types of pods. The problem I am having is that if I delete a pod to make it pull a fresh image (all pods are managed by deployments, so if I delete a pod it will create a new one), for a while there are two pods, one shows as terminating and the other as running in kubectl get pods output. I want to make sure that the command above selects the pod that is running and not the one terminating. I thought --field-selector=status.phase=Running flag would do it, but it does not. Apparently even if the pod is in the process of terminating it still reports Running status in status.phase field. What can I use to filter out terminating pods?
Use this one
$ kubectl exec -it $(kubectl get pods --selector=run=${service} | grep "running" | awk '{print $1}') -- bash;
or
$ kubectl exec -it $(kubectl get pods --selector=run=${service} -o=jsonpath='{.items[?(#.status.phase==“Running”)].metadata.name}') -- bash;
Ref: https://kubernetes.io/docs/reference/kubectl/jsonpath/

Resources