Get names of all deployment configs with no running pods - kubernetes

Is there a simple method (that won't require googling at every use) to get names of all deployment configs with no running pods (scaled to 0) in Kubernetes / Openshift? Methods without JSON tokens and awk please.
The docs of oc get dc --help are way too long to decipher for the occasional need.

The only CLI arg for advanced filtering without working with JSON is a --field-selector, but it has a limited scope which not include spec.replicas field.
So, there will be some magic around JSON with other flag - jsonpath.
Here is a command to filter and print names of all deployments which are scaled to 0:
kubectl get deployments --all-namespaces -o=jsonpath='{range .items[?(#.spec.replicas==0)]}{.metadata.name}{"\n"}{end}'
Jsonpath reference is here.

Related

How to get the full name of a pod by both its creation date and part of its name?

In my namespace, I have several pods named with the same prefix, followed by the random string. There are also other pods, named differently. The result of kubectl get pods would look something like this:
service-job-12345abc
service-job-abc54321
other-job-54321cba
I need to find the nameof the most recently created pod starting with "service-job-".
I found this thread, which helps getting the name of the most recent pod in general. This one gets me the complete names of pods starting with a specific prefix.
What I struggle with is combining these two methods. With each one, I seem to lose the information I need to perform the other one.
Note: I am not an administrator of the cluster, so I cannot change anything about the naming etc. of the pods. The pods could also be in any possible state.
This works as you expect:
kubectl get pods --sort-by=.metadata.creationTimestamp --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}' | grep service-job- | head -1

Memory effective way to monitor change of Kubernetes objects in a namespace

I am working with kubernetes and kubectl commands, and am able to get a list of namespaces, and then can get the resources inside those namespaces. Question is, is there an effective way to monitor all resources (CRDs especially) in a certain namespace for changes? I know I could do this:
kubectl get myobjecttype -n <user-account-1>
and then check timestamps with a separate command, but that seems resource-taxing.
You might be looking for the Kubernetes Watch API.
In fact, you make a List request (see API reference for e.g. Pods) and add the watch=1 query parameter to get a continuous stream of changes to the specified resources.
kubectl also supports watches with the -w/--watch flag:
kubectl get myobjecttype -n <user-account-1> -w

GKE pod replica count in cluster

How can we obtain the gke pod counts running in the cluster? I found there are ways to get node count but we needed pod count as well. it will be better if we can use something with no logging needed in gcp operations.
You can do it with Kubernetes Python Client library as shown in this question, posted by Pradeep Padmanaban C, where he was looking for more effective way of doing it, but his example is actually the best what you can do to perform such operation as there is no specific method which would allow you just to count pods without retrieving their entire json manifests:
from kubernetes import client , config
config.load_kube_config()
v1= client.CoreV1Api()
ret_pod = v1.list_pod_for_all_namespaces(watch=False)
print(len(ret_pod.items))
You can also use a different method, which allows to retrieve pods only from specific namespace e.g.:
list_namespaced_pod("default")
In kubectl way you can do it as follows (as proposed here by RammusXu):
kubectl get pods --all-namespaces --no-headers | wc -l
You can directly access the kubernetes API using a restful API call. You will need to make sure you provide the authentication token in your call by including a bearer token.
Once you are able to query the api server directly, you can use GET <master_endpoint>/api/v1/pods to list all the pods in the cluster. You can also search for specific namespaces by specifying the namespace /api/v1/namespaces/<namespace>/pods.
Keep in mind that the kubectl cli tool is just a wrapper for API calls, each kubectl command will form a RESTful API call in a similar format to the one listed above, so any interaction you have with the cluster using kubectl can also be achieved through RESTful API calls

Can somene explain the different Kubernetes yaml files and types?

First off, I'm completely new with Kubernetes so I may have missed something completely obvious but the documentation is exactly helping, so I'm turning to you guys for help.
I'm trying to figure out just how many types of "deployment files" there are for Kubernetes. I call them "deployment files" because I really don't know what else to call them and they're usually associated with a deployment.
So far, every yml/yaml file I've seen start like this:
apiVersion:
kind: << this is what I'm asking about >>
metadata:
And so far I have seen this many "kind"(s)
ClusterConfig
ClusterRole
ClusterRoleBinding
CronJob
Deployment
Job
PersistentVolumeClaim
Pod
ReplicationController
Role
RoleBinding
Secret
Service
ServiceAccount
I'm sure there are many more. But I can't seem to find a location where they are listed and the contexts broken down.
So what I want to know is this,
Where can I find an explanation for these yaml files?
Where can I learn about the different kinds?
Where can I get a broken down explanation of the minimum required fields/values are for any of these?
Are there templates for these files?
Thanks
This question will need a blog to answer but still in short you can try these options and command to learn from your kubectl CLI.
Learn to use kubectl explain command which shows you a list of Kubernetes objects:
$ kubectl explain
You can get detailed information about any of listed resources using this syntax
`$ kubectl explain pod
$ kubectl explain pod.spec
$ kubectl explain pod.spec.containers`
Or you can get yam template of the object by adding --recursive flag to explain command.
$ kubectl explain pod --recursive
This will also give you official document link.
So in short running kubectl explain with recursive option will list every thing.
When you are talking about specific yaml file containing the definition of specific kubernetes object, you can call them yaml manifests or simply yaml definition files. Using word Deployment for all of them isn't a good idea as there is already specific resource type defined and called by this name in kubernetes. So it's better you don't call them all deployments for consistency.
I'm sure there are many more. But I can't seem to find a location
where they are listed and the contexts broken down.
Yes, there are a lot more of them and you can list those which are available by running:
kubectl api-resources
These different objects are actually called api-resources. As you can see they are listed in three columns: NAME, SHORTNAMES, APIGROUP, NAMESPACED and KIND
NAME SHORTNAMES APIGROUP NAMESPACED KIND
bindings true Binding
componentstatuses cs false ComponentStatus
configmaps cm true ConfigMap
endpoints ep true Endpoints
events ev true Event
limitranges limits true LimitRange
namespaces ns false Namespace
nodes no false Node
Note that the name of resource corresponds to its KIND but it is slightly different. NAME simply describes resource types as we are referring to them e.g. using kubectl command line utility. Just to give one example, when you want to list pods available in your cluster you simply type kubectl get pods. You don't have to use resource kind i.e. Pod in this context. You can but you don't have to. So kubectl get Pod or kubectl get ConfigMap will also return desired result. You can also refer to them by their shournames so kubectl get daemonsets and kubectl get ds are equivalent.
It's totally different when it comes to specific resource/object definition. In context of yaml definition file we must to use proper KIND of the resource. They are mostly start with capital letter and are written by co called CamelCase but there are exceptions from this rule.
I really recommend you to familiarize with kubernetes documentation. It is very user-friendly and nicely explains both key kubernetes concepts as well as all very tiny details.
Here you have even more useful commands for exploring API resources:
kubectl api-resources --namespaced=true # All namespaced resources
kubectl api-resources --namespaced=false # All non-namespaced resources
kubectl api-resources -o name # All resources with simple output (just the resource name)
kubectl api-resources -o wide # All resources with expanded (aka "wide") output
kubectl api-resources --verbs=list,get # All resources that support the "list" and "get" request verbs
kubectl api-resources --api-group=extensions # All resources in the "extensions" API group
As #wargre already suggested in his comment, kubernetes official documentetion is definitely the best place to start as you will find there very detailed description of every resource.
Understanding Kubernetes Objects
You may start from reading this article: Understanding Kubernetes Objects
Kubernetes Objects are persistent entities in the Kubernetes system. Kubernetes uses these entities to represent the state of your cluster. Specifically, they can describe:
What containerized applications are running (and on which nodes)
The resources available to those applications
The policies around how those applications behave, such as restart policies, upgrades, and fault-tolerance
A Kubernetes object is a “record of intent”–once you create the object, the Kubernetes system will constantly work to ensure that object exists. By creating an object, you’re effectively telling the Kubernetes system what you want your cluster’s workload to look like; this is your cluster’s desired state.
K8s API reference
A detailed description of all objects can be found in the Kubernetes API reference guide.

Get replica set of the deployment

I can get the ReplicaSet if given the replica-set-name using the api as below:
GET /apis/apps/v1/namespaces/{namespace}/replicasets/{name}
But how can I get the ReplicaSet based on the deployment?
Any help is appreciated.
Thank you
But how can I get the ReplicaSet based on the deployment?
With quite some gymnastics... If you inspect how kubectl does it (by executing kubectl -n my-namespace describe deploy my-deployment --v=9) you will see that it dos the following:
first gets deployment details with: /apis/extensions/v1beta1/namespaces/my-namespace/deployments/my-deployment. From there it gets labels for replicaset selection.
then gets replicaset details using labels from deployment in previous step (say labels were my-key1:my-value1 and my-key2:my-value2) like so: /apis/extensions/v1beta1/namespaces/my-namespace/replicasets?labelSelector=my-key1%3Dmy-value1%2Cmy-key2%3Dmy-value2
Funny part here begins with extracting multiple labels from deployment output and formatting them for replicaset call, and that is task for grep, awk, jq or even python, depending on your actual use case (from bash, python, some client or whatever...)