{"id":14483453,"url":"https://github.com/eldada/kubernetes-scripts","last_synced_at":"2025-05-15T16:09:51.489Z","repository":{"id":44396884,"uuid":"230422381","full_name":"eldada/kubernetes-scripts","owner":"eldada","description":"A collection of scripts and commands for various Kubernetes tasks","archived":false,"fork":false,"pushed_at":"2025-03-09T13:53:28.000Z","size":78,"stargazers_count":414,"open_issues_count":0,"forks_count":175,"subscribers_count":18,"default_branch":"master","last_synced_at":"2025-03-31T21:44:52.695Z","etag":null,"topics":["hacktoberfest","kubernetes","kubernetes-scripts"],"latest_commit_sha":null,"homepage":"","language":"Shell","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/eldada.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-12-27T10:17:35.000Z","updated_at":"2025-03-09T13:53:31.000Z","dependencies_parsed_at":"2024-10-30T11:35:42.490Z","dependency_job_id":null,"html_url":"https://github.com/eldada/kubernetes-scripts","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eldada%2Fkubernetes-scripts","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eldada%2Fkubernetes-scripts/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eldada%2Fkubernetes-scripts/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eldada%2Fkubernetes-scripts/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/eldada","download_url":"https://codeload.github.com/eldada/kubernetes-scripts/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247737770,"owners_count":20987718,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["hacktoberfest","kubernetes","kubernetes-scripts"],"created_at":"2024-09-03T00:01:46.949Z","updated_at":"2025-04-07T22:06:03.156Z","avatar_url":"https://github.com/eldada.png","language":"Shell","funding_links":[],"categories":["Shell"],"sub_categories":[],"readme":"# Kubernetes Scripts\nA collection of scripts and commands for various tasks in [Kubernetes](https://kubernetes.io/).\u003cbr\u003e\nThese were all written during my work with Kubernetes on various project. Enjoy and share. Contributions are more than welcome!\n\n## Usage\nEach script has a `usage` function. See usage with\n```shell script\n\u003cscript\u003e --help\n```\n\n## Scripts\n* [countPodsAndContainerPerNodeCSV.sh](countPodsAndContainerPerNodeCSV.sh): Count number of pods and containers per node. Print in CSV format.\n* [findEmptyNamespaces.sh](findEmptyNamespaces.sh): Loop over all namespaces in a cluster and find empty ones.\n* [getPodsLoad.sh](getPodsLoad.sh): Get formatted results of pods in a namespace underlying node's load average (using cat /proc/loadavg).\n* [getPodsTopCSV.sh](getPodsTopCSV.sh): Get a pod's cpu and memory usage (optionally per container) written as CSV formatted file.\n* [getResourcesCSV.sh](getResourcesCSV.sh): Get all pods resources requests, limits and actual usage per container in a CSV format with values normalized.\n* [getRestartingPods.sh](getRestartingPods.sh): Get all pods (all or single namespace) that have restarts detected in one or more containers. Formatted in CSV.\n* [podReady.sh](podReady.sh): Simple script to check if pod is really ready. Check status is 'Running' and that all containers are ready. Returns 0 if ready. Returns 1 if not ready.\n* [getNodesLoadCSV.sh](getNodesLoadCSV.sh): Traverse over the `kube-proxy` pods to get the nodes load average and number of CPUs in a CSV format. Will also mark high load node with big `YES` in the output.\n* [runCommandOnPods.sh](runCommandOnPods.sh): Run a command on a list of pods.\n* [canIdo.sh](canIdo.sh): Check all or some permissions current user has in a namespace on all or some resources using the `kubectl auth can-i` command.\n\n## YAML\n* [memory.yaml](yaml/memory.yaml): A pod using a given block of memory for a given time.\u003cbr\u003e\n* [podWithTools.yaml](yaml/podWithTools.yaml): A pod with some basic tools (`vi` and `curl`) for easy debugging.\u003cbr\u003e\n* [podWithHostFS.yaml](yaml/podWithHostFS.yaml): A pod with the host root file system mounted into it.\u003cbr\u003e\n* [podmanPod.yaml](yaml/podmanPod.yaml): A pod with [podman](https://podman.io/) in it.\u003cbr\u003e\n* [superPod](yaml/superPod.yaml): A pod with the host file system and process IDs mounted for allowing to manipulate the host system and restarting kubelet.\u003cbr\u003e\n  **WARNING:** There is danger of corrupting your Kubernetes host. Use with extra care!\n* [kind-config.yaml](yaml/kind-config.yaml): An example [kind](https://kind.sigs.k8s.io/) configuration for a multi node K8s cluster\n  **WARNING:** There is danger of corrupting your Kubernetes host. Use with extra care!\n\n## Commands\n### Kubectl\n#### See all cluster nodes load (top)\n```shell script\nkubectl top nodes\n```\n\n#### Get cluster events\n```shell script\n# All cluster\nkubectl get events\n\n# Specific namespace events\nkubectl get events --namespace=kube-system\n```\n\n#### Get all cluster nodes IPs and names\n```shell script\n# Single call to K8s API\nkubectl get nodes -o json | grep -A 12 addresses\n\n# A loop for more flexibility\nfor n in $(kubectl get nodes -o name); do \\\n  echo -e \"\\nNode ${n}\"; \\\n  kubectl get ${n} -o jsonpath='{.status.addresses}'; \\\ndone\n```\n\n#### See all cluster nodes CPU and Memory requests and limits\n```shell script\n# With node names\nkubectl describe nodes | grep -A 3 \"Name:\\|Resource .*Requests .*Limits\" | grep -v \"Roles:\"\n\n# Just the resources\nkubectl describe nodes | grep -A 3 \"Resource .*Requests .*Limits\"\n``` \n\n##### Using kube-capacity\nThere is a great CLI for getting a cluster capacity and utilization - [kube-capacity](https://github.com/robscott/kube-capacity).\u003cbr\u003e\nInstall as described in the [installation](https://github.com/robscott/kube-capacity#installation) section.\n```shell script\n# Get cluster current capacity\nkube-capacity\n\n# Get cluster current capacity with pods breakdown\nkube-capacity --pods\n\n# Get cluster current capacity and utilization\nkube-capacity --util\n\n# Displaying available resources\nkube-capacity --available\n\n# Roll over all clusters in your kubectl contexts\nfor a in $(kubectl ctx); do echo -e \"\\n---$a\"; kubectl ctx $a; kube-capacity; done\n\n# Roll over all clusters in your kubectl contexts and get just summary of each cluster\nfor a in $(kubectl ctx); do echo -e \"\\n---$a\"; kubectl ctx $a; kube-capacity| grep -B 1 \"\\*\"; done\n```\n\n#### Get all labels attached to all pods in a namespace\n```shell script\nfor a in $(kubectl get pods -n namespace1 -o name); do \\\n  echo -e \"\\nPod ${a}\"; \\\n  kubectl -n namespace1 describe ${a} | awk '/Labels:/,/Annotations/' | sed '/Annotations/d'; \\\ndone\n```\n\n#### Forward local port to a pod or service\n```shell script\n# Forward localhost port 8080 to a specific pod exposing port 8080\nkubectl port-forward -n namespace1 web 8080:8080\n\n# Forward localhost port 8080 to a specific web service exposing port 80\nkubectl port-forward -n namespace1 svc/web 8080:80\n```\n\n#### Port forwarding\n* A great tool for port forwarding all services in a namespace + adding aliases to `/etc/hosts` is [kubefwd](https://github.com/txn2/kubefwd).\nNote that this requires root or sudo to allow temporary editing of `/etc/host`.\n```shell script\n# Port forward all service in namespace1\nkubefwd svc -n namespace1\n```\n\n#### Extract and decode a secret's value\n```shell script\n# Get the value of the postgresql password\nkubectl get secret -n namespace1 my-postgresql -o jsonpath=\"{.data.postgres-password}\" | base64 --decode\n```\n\n#### Copy secret from `namespace1` to `namespace2`\n```shell script\nkubectl get secret my-secret --namespace namespace1 -o yaml | sed \"/namespace:/d\" | kubectl apply --namespace=namespace2 -f -\n```\n\n#### Create an Ubuntu pod\nA one liner to create an Ubuntu pod that will just wait forever. \n```shell script\n# Create the pod\ncat \u003c\u003cZZZ | kubectl apply -f -\napiVersion: v1\nkind: Pod\nmetadata:\n  name: my-ubuntu-pod\nspec:\n  containers:\n  - name: my-ubuntu-container\n    image: eldada.jfrog.io/docker/ubuntu:22.04\n    command:\n    - 'bash'\n    - '-c'\n    - 'while true; do date; sleep 60; done'\nZZZ\n\n# Shell into the pod\nkubectl exec -it my-ubuntu-pod bash\n\n# Delete the pod once done\nkubectl delete pod my-ubuntu-pod\n```\n\n#### Start a shell in a temporary pod\nNote - Pod will terminate once exited\n```shell script\n# Ubuntu\nkubectl run my-ubuntu --rm -i -t --restart=Never --image ubuntu -- bash\n\n# CentOS\nkubectl run my-centos --rm -i -t --restart=Never --image centos:8 -- bash\n\n# Alpine\nkubectl run my-alpine --rm -i -t --restart=Never --image alpine:3.10 -- sh\n\n# Busybox\nkubectl run my-busybox --rm -i -t --restart=Never --image busybox -- sh\n```\n\n#### Get formatted list of containers and container images\nUseful for listing all running containers in your cluster\n```shell script\n# Example 1 - just the container names\nkubectl get pods -A -o jsonpath='{..containers[*].name}' | tr -s ' ' '\\n'\n# With sorting and unique names\nkubectl get pods -A -o jsonpath='{..containers[*].name}' | tr -s ' ' '\\n' | sort | uniq\n\n# Example 2 - container images and tags\nkubectl get pods -A -o=jsonpath='{..containers[*].image}' | tr -s ' ' '\\n'\n# With sorting and unique names\nkubectl get pods -A -o=jsonpath='{..containers[*].image}' | tr -s ' ' '\\n' | sort | uniq\n\n# Example 3 - pod and its container images\nkubectl get pods -A -o=jsonpath='{range .items[*]}{\"\\n\"}{.metadata.name}{\":\\n\"}{range .spec.containers[*]}{.name},{.image}{\"\\n\"}{end}{end}'\n\n# Example 4 - pod and its container images with their resources requests (cpu and memory)\nkubectl get pods -A -o=jsonpath='{range .items[*]}{\"\\n\"}{.metadata.name}{\":\\n\"}{range .spec.containers[*]}{.name},{.image}{.resources.requests.cpu},{.resources.requests.memory}{\"\\n\"}{end}{end}'\n\n```\nLook into [a few more examples](https://kubernetes.io/docs/tasks/access-application-cluster/list-all-running-container-images) of listing containers\n\n#### Get list of pods sorted by restart count\n* Option 1 for all pods (Taken from [kubectl cheatsheet](https://kubernetes.io/docs/reference/kubectl/cheatsheet/#viewing-finding-resources))\n```shell script\nkubectl get pods -A --sort-by='.status.containerStatuses[0].restartCount'\n```\n\n* Option 2 with a filter, and a CSV friendly output\n```shell script\nkubectl get pods -A | grep my-app | awk '{print $5 \", \" $1 \", \" $6}'  | sort -n -r\n```\n\n#### Get current replica count on all HPAs (Horizontal Pod Autoscaling)\n```shell script\nkubectl get hpa -A -o=custom-columns=NAME:.metadata.name,REPLICAS:.status.currentReplicas | sort -k2 -n -r\n```\n\n#### List non-running pods\n```shell script\nkubectl get pods -A --no-headers | grep -v Running | grep -v Completed\n```\n\n#### Top Pods by CPU or memory usage\n```shell script\n# Top 20 pods by highest CPU usage\nkubectl top pods -A --sort-by=cpu | head -20\n\n# Top 20 pods by highest memory usage\nkubectl top pods -A --sort-by=memory | head -20\n\n# Roll over all kubectl contexts and get top 20 CPU users\nfor a in $(kubectl ctx); do echo -e \"\\n---$a\"; kubectl ctx $a; kubectl top pods -A --sort-by=cpu | head -20; done\n```\n\n#### Debugging Pods and Nodes\nThis section is based on [debugging pods using ephemeral containers](https://kubernetes.io/docs/tasks/debug/debug-application/debug-running-pod/#ephemeral-container-example)\nand [kubectl node debug](https://kubernetes.io/docs/tasks/debug/debug-cluster/kubectl-node-debug/)\n\n##### Pod Debugging\n```shell script\n# Attach an ephemeral container to an existing container in a pod for debugging\nkubectl debug -it my-pod --image=ubuntu --target=my-container\n```\n\n##### Node Debugging\n```shell script\n# Debug a node with a new pod attached to it\n# IMPORTANT to delete the pods after exiting it. It will not be deleted automatically (although it will be in the \"Completed\" state)\nkubectl debug node/\u003cmynode\u003e -it --image=ubuntu\n```\n### Helm\n\n#### Helm template\nView the templates generated by `helm install`. Useful for seeing the actual templates generated by helm before deploying.\u003cbr\u003e\nCan also be used for deploying the templates generated when cannot use Tiller\n```shell script\nhelm template \u003cchart\u003e\n```\n\n#### Debug helm install\n* Debug a `helm install`. Useful for seeing the actual values resolved by helm before deploying\n```shell script\nhelm install --debug --dry-run \u003cchart\u003e\n```\n\n### Rolling restarts\nRoll a restart across all resources managed by a Deployment, DaemonSet or StatefulSet with **zero downtime**\u003cbr\u003e\n**IMPORTANT**: For a Deployment or StatefulSet, a zero downtime is possible only if initial replica count is **higher than 1**!\n```shell script\n# Deployment\nkubectl -n \u003cnamespace\u003e rollout restart deployment \u003cdeployment-name\u003e\n\n# DaemonSet\nkubectl -n \u003cnamespace\u003e rollout restart daemonset \u003cdaemonset-name\u003e\n\n# StatefulSet\nkubectl -n \u003cnamespace\u003e rollout restart statefulsets \u003cstatefulset-name\u003e\n```\n\n### Mark Nodes with some roles for visibility (ex. EKS nodes marked with the LifeCycle,NodeType)\n* Most use of it can be gained with some GUI client (Lens), still \"k get nodes\" shows ROLE fields as well\n```shell\nfor n in $(kubectl get nodes -o 'jsonpath={.items[*].metadata.name}') ; do\n  lb=\"\"\n  for a in $(kubectl label --list nodes $n | sort | grep -e NodeType -e lifecycle | cut -d= -f 2); do\n    lb=\"${lb}$a\"\n  done\n  kubectl label nodes $n node-role.kubernetes.io/$lb=\ndone\n```\n\n## A Multi Node Kubernetes cluster in Mac with Kind\nTo run a multi node Kubernetes cluster in Mac with [Kind](https://kind.sigs.k8s.io/), do the following (assuming Docker Desktop is already installed)\n- Install `kind` as described in [kind installation](https://kind.sigs.k8s.io/docs/user/quick-start/#installation)\n- Start a local, three worker nodes cluster using the [kind-config.yaml](yaml/kind-config.yaml) config file\n```shell\nkind create cluster --config yaml/kind-config.yaml --name demo\n```\n\nDelete the cluster with\n```shell\nkind delete cluster --name demo\n```\n\n## Metrics Server in Kubernetes on Docker Desktop or Kind for Mac\nTo get around issue with certificates in your local Docker Desktop or Kind Kubernetes\n\nInstall a `metrics-server`\n```shell\nkubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml\n```\n\nPatch the `metrics-server` Deployment with the fix\n```shell\nkubectl patch deployment metrics-server -n kube-system --patch-file yaml/metrics-server-patch.yaml\n```\n\n**OR** Edit the `metrics-server` deployment directly and add `--kubelet-insecure-tls` to the `args` key:\n```yaml\nspec:\n  containers:\n  - args:\n    - --cert-dir=/tmp\n    - --secure-port=443\n    - --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname\n    - --kubelet-use-node-status-port\n    - --metric-resolution=15s\n    - --kubelet-insecure-tls\n```\n\n### Resources\nMost of the code above is self experimenting and reading the docs. Some are copied and modified to my needs from other resources...\n* https://kubernetes.io/docs/reference/kubectl/cheatsheet/\n* https://medium.com/flant-com/kubectl-commands-and-tips-7b33de0c5476\n* https://github.com/robscott/kube-capacity\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feldada%2Fkubernetes-scripts","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Feldada%2Fkubernetes-scripts","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feldada%2Fkubernetes-scripts/lists"}