Kubectl: различия между версиями
Sirmax (обсуждение | вклад) |
Sirmax (обсуждение | вклад) |
||
(не показано 12 промежуточных версий этого же участника) | |||
Строка 2: | Строка 2: | ||
[[Категория:kubectl]] |
[[Категория:kubectl]] |
||
=Шпаргалка по <code>kubectl</code>= |
=Шпаргалка по <code>kubectl</code>= |
||
+ | много примеров тут: https://kubernetes.io/docs/reference/kubectl/quick-reference/ |
||
==Частные случаи== |
==Частные случаи== |
||
===<code>--show-managed-fields </code> - посмотреть какие были операции с объектом=== |
===<code>--show-managed-fields </code> - посмотреть какие были операции с объектом=== |
||
Строка 104: | Строка 105: | ||
===Список контейнеров в поде=== |
===Список контейнеров в поде=== |
||
Для каждого контейнера pod-name, container-image container-name<BR> |
Для каждого контейнера pod-name, container-image container-name<BR> |
||
− | Довольно коряво, конечно |
+ | Довольно коряво, конечно, но можно использовать как основу для своих скриптов |
<PRE> |
<PRE> |
||
Строка 111: | Строка 112: | ||
-n osh-system \ |
-n osh-system \ |
||
--selector=app.kubernetes.io/instance=openstack-operator \ |
--selector=app.kubernetes.io/instance=openstack-operator \ |
||
− | -o=jsonpath='{range .items[*]}{"\nStart output for POD: "}{.metadata.name}{"\nContaines:\n"}{range .spec.containers[*]}{.image}{"\t"}{.name}{"\n"}{end}{"End output for POD"}{.metadata.name}{\n"}{end}' |
+ | -o=jsonpath='{range .items[*]}{"\nStart output for POD: "}{.metadata.name}{"\nContaines:\n"}{range .spec.containers[*]}{.image}{"\t"}{.name}{"\n"}{end}{"End output for POD: "}{.metadata.name}{"\n"}{end}' |
</PRE> |
</PRE> |
||
Пример вывода: |
Пример вывода: |
||
<PRE> |
<PRE> |
||
− | openstack-controller-7896bc6d4d-l5mrz |
+ | Start output for POD: openstack-controller-7896bc6d4d-l5mrz |
+ | Containes: |
||
+ | 127.0.0.1:44301/openstack/openstack-controller:0.14.18 osdpl |
||
127.0.0.1:44301/openstack/openstack-controller:0.14.18 secrets |
127.0.0.1:44301/openstack/openstack-controller:0.14.18 secrets |
||
127.0.0.1:44301/openstack/openstack-controller:0.14.18 health |
127.0.0.1:44301/openstack/openstack-controller:0.14.18 health |
||
Строка 125: | Строка 128: | ||
127.0.0.1:44301/openstack/openstack-controller:0.14.18 osdplsecret |
127.0.0.1:44301/openstack/openstack-controller:0.14.18 osdplsecret |
||
127.0.0.1:44301/openstack/openstack-controller:0.14.18 tf-secrets |
127.0.0.1:44301/openstack/openstack-controller:0.14.18 tf-secrets |
||
+ | End output for POD: openstack-controller-7896bc6d4d-l5mrz |
||
− | openstack-controller-admission-5d78bf4d84-jmghf |
+ | Start output for POD: openstack-controller-admission-5d78bf4d84-jmghf |
+ | Containes: |
||
+ | 127.0.0.1:44301/openstack/openstack-controller:0.14.18 openstack-operator |
||
+ | End output for POD: openstack-controller-admission-5d78bf4d84-jmghf |
||
− | openstack-controller-exporter-9f775b56f-gnntj |
+ | Start output for POD: openstack-controller-exporter-9f775b56f-gnntj |
+ | Containes: |
||
+ | 127.0.0.1:44301/openstack/openstack-controller:0.14.18 exporter |
||
+ | End output for POD: openstack-controller-exporter-9f775b56f-gnntj |
||
+ | </PRE> |
||
+ | ===Найти все поды по метке (<code>-l</code>) и вернуть список имеджей=== |
||
+ | <code>kubectl get pods --all-namespaces -o=jsonpath='{..image}' -l app=prometheus</code> |
||
+ | ===Число Pod на node=== |
||
+ | <PRE> |
||
+ | kubectl get pod --all-namespaces -o json | jq '.items | group_by(.spec.nodeName) | map({"nodeName": .[0].spec.nodeName, "count": length}) | sort_by(.count)' |
||
+ | </PRE> |
||
+ | Пример результата |
||
+ | <PRE> |
||
+ | [ |
||
+ | ... |
||
+ | { |
||
+ | "nodeName": "os-control-1", |
||
+ | "count": 55 |
||
+ | }, |
||
+ | { |
||
+ | "nodeName": "os-control-3", |
||
+ | "count": 70 |
||
+ | } |
||
+ | ] |
||
</PRE> |
</PRE> |
||
− | Get containers by Pod-Label (Return the container Image) kubectl get pods --all-namespaces -o=jsonpath="{..image}" -l app=prometheus |
||
+ | ===Список запущенных и не запущенных POD=== |
||
− | Pod count per node kubectl get po --all-namespaces -o json | jq '.items | group_by(.spec.nodeName) | map({"nodeName": .[0].spec.nodeName, "count": length}) | sort_by(.count)' |
||
+ | <code>kubectl get pods --all-namespaces --field-selector=status.phase=Running</code> |
||
+ | <PRE> |
||
+ | NAMESPACE NAME READY STATUS RESTARTS AGE |
||
+ | ceph-lcm-mirantis ceph-controller-567884bc4f-h6ppp 2/2 Running 0 4d1h |
||
+ | ceph-lcm-mirantis ceph-disk-daemon-22cl2 1/1 Running 1 (4d17h ago) 26d |
||
+ | ceph-lcm-mirantis ceph-disk-daemon-gcsnz 1/1 Running 1 (4d17h ago) 26d |
||
+ | ceph-lcm-mirantis ceph-disk-daemon-wwvrk 1/1 Running 1 (4d17h ago) 26d |
||
+ | ceph-lcm-mirantis ceph-maintenance-controller-76669864dc-njppm 1/1 Running 0 4d1h |
||
+ | ceph-lcm-mirantis ceph-request-controller-7d7d9ffc77-jz6lq 3/3 Running 0 4d1h |
||
+ | ceph-lcm-mirantis ceph-status-controller-556574b56b-bgh78 1/1 Running 0 4d1h |
||
+ | kaas client-certificate-controller-59546996f-dqmhf 1/1 Running 0 4d1h |
||
+ | ... |
||
+ | </PRE> |
||
− | + | <code>kubectl get pods --all-namespaces --field-selector='status.phase!=Running</code> |
|
+ | <PRE> |
||
− | |||
+ | NAMESPACE NAME READY STATUS RESTARTS AGE |
||
− | Get !Running pods kubectl get pods --all-namespaces --field-selector='status.phase!=Running |
||
+ | openstack aodh-db-purge-28472041-2plwc 0/1 Completed 0 6h24m |
||
− | |||
+ | openstack aodh-ks-user-pznnt 0/1 Completed 0 4d2h |
||
− | Get all pods in All-namespaces, return mem and cpu (FOR EACH POD!) |
||
+ | openstack barbican-db-purge-28471921-st487 0/1 Completed 0 8h |
||
+ | openstack barbican-ks-user-k9c8s 0/1 Completed 0 4d2h |
||
+ | openstack ceilometer-ks-user-kh7mh 0/1 Completed 0 4d2h |
||
+ | ... |
||
+ | </PRE> |
||
+ | ===Get all pods in All-namespaces, return mem and cpu (FOR EACH POD!)=== |
||
+ | <PRE> |
||
kubectl get po -n elasticsearch --selector=service=elasticsearch-data -o=jsonpath="{range .items[*]}{.metadata.namespace}:{.metadata.name}{'\n'}{range .spec.containers[*]} {.resources.requests.cpu}{'\t'}{end}{'\n'}{end}" |
kubectl get po -n elasticsearch --selector=service=elasticsearch-data -o=jsonpath="{range .items[*]}{.metadata.namespace}:{.metadata.name}{'\n'}{range .spec.containers[*]} {.resources.requests.cpu}{'\t'}{end}{'\n'}{end}" |
||
+ | </PRE> |
||
− | Describe a POD and list its IP kubectl describe pod 'kube-dns-2948363707' -n kube-system | grep IP | sed -E 's/IP:[[:space:]]+//' |
||
− | Get the external IPs of PODs |
+ | ===Get the external IPs of PODs === |
+ | kubectl get nodes --all-namespaces -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}' |
||
+ | ===Show the images and their versions for each pod === |
||
− | Show the images and their versions for each pod kubectl get pods --all-namespaces -o jsonpath="{..image}" | tr -s '[[:space:]]' '\n' | sort | uniq -c kubectl get pods --all-namespaces -o jsonpath="{.items[*].spec.containers[*].image}" kubectl get pods -n default --field-selector=status.phase=Running --selector=app=my-service -o jsonpath="{..image}" | tr -s '[[:space:]]' '\n' | sort | uniq -c |
||
+ | <PRE> |
||
+ | kubectl get pods --all-namespaces -o jsonpath="{..image}" | tr -s '[[:space:]]' '\n' | sort | uniq -c kubectl get pods --all-namespaces -o jsonpath="{.items[*].spec.containers[*].image}" kubectl get pods -n default --field-selector=status.phase=Running --selector=app=my-service -o jsonpath="{..image}" | tr -s '[[:space:]]' '\n' | sort | uniq -c |
||
+ | </PRE> |
||
+ | ===Delete terminated/evicted pods === |
||
+ | <PRE> |
||
+ | kubectl get po --selector=app=devops-logstash-service --field-selector=status.phase=Failed --no-headers -n elasticsearch | awk '{ print $1 }' | xargs -I {} kubectl delete po -n elasticsearch {} |
||
+ | </PRE> |
||
+ | ==Deployments== |
||
− | Delete terminated/evicted pods kubectl get po --selector=app=devops-logstash-service --field-selector=status.phase=Failed --no-headers -n elasticsearch | awk '{ print $1 }' | xargs -I {} kubectl delete po -n elasticsearch {} |
||
+ | Get deployments, output as JSON, format output with JQ |
||
− | Deployments |
||
+ | <PRE> |
||
+ | kubectl get deployment --namespace=kube-system -o=json | jq '.items[].metadata.labels' |
||
+ | </PRE> |
||
+ | Get K8S Deployments matching the selector (look for key k8s-app with value heapster) |
||
+ | <PRE> |
||
+ | kubectl get deployment --all-namespaces --selector=k8s-app=heapster kubectl get svc --namespace=kube-system --selector=name=tiller |
||
+ | </PRE> |
||
+ | Scale a deployment |
||
− | Get deployments, output as JSON, format output with JQ kubectl get deployment --namespace=kube-system -o=json | jq '.items[].metadata.labels' |
||
+ | <PRE> |
||
+ | kubectl scale -n kube-system --replicas=0 'deployments/kube-dns' kubectl scale -n kube-system --replicas=2 'deployments/kube-dns' |
||
+ | </PRE> |
||
+ | Export the YAML file of a deployment (for reuse, modification, etc,.) |
||
+ | <PRE> |
||
+ | kubectl get deployments ghost --export -n ghost -o yaml > ghost.yaml |
||
+ | </PRE> |
||
+ | ==Replicasets== |
||
− | Get K8S Deployments matching the selector (look for key k8s-app with value heapster) kubectl get deployment --all-namespaces --selector=k8s-app=heapster kubectl get svc --namespace=kube-system --selector=name=tiller |
||
+ | ===Get all replicasets sorted by the number of replicas=== |
||
− | Scale a deployment kubectl scale -n kube-system --replicas=0 'deployments/kube-dns' kubectl scale -n kube-system --replicas=2 'deployments/kube-dns' |
||
+ | <PRE> |
||
+ | kubectl get rs -n elasticsearch --sort-by='.spec.replicas' |
||
+ | </PRE> |
||
+ | ===Get all replicasets where replicas==0 in a specific namespace=== |
||
+ | <PRE> |
||
+ | kubectl get rs -n elasticsearch -o json | jq -r '.items[] |select(.status.replicas==0) | .metadata.name' |
||
+ | </PRE> |
||
+ | ===Delete all replicasets that equal 0 in a specific namespace=== |
||
+ | <PRE> |
||
+ | kubectl get rs -n elasticsearch -o json | jq -r '.items[] |select(.status.replicas==0) | .metadata.name' | xargs -I {} kubectl delete rs {} |
||
+ | </PRE> |
||
+ | ==Services== |
||
− | Export the YAML file of a deployment (for reuse, modification, etc,.) kubectl get deployments ghost --export -n ghost -o yaml > ghost.yaml |
||
+ | ===Get the self-link for a service using JSONPATH to format the output=== |
||
− | Replicasets |
||
+ | <PRE> |
||
+ | kubectl get svc heapster --namespace=kube-system -o=jsonpath={.metadata.selfLink} |
||
+ | </PRE> |
||
+ | ===Get 'service' external LB address=== |
||
− | Get all replicasets sorted by the number of replicas kubectl get rs -n elasticsearch --sort-by='.spec.replicas' |
||
+ | <PRE> |
||
− | |||
− | + | kubectl get svc --namespace=kube-system -o=json | jq -r '.items[] | .status.loadBalancer.ingress[0]' |
|
+ | </PRE> |
||
− | |||
+ | ===List all services in cluster and their nodePorts=== |
||
− | Delete all replicasets that equal 0 in a specific namespace kubectl get rs -n elasticsearch -o json | jq -r '.items[] |select(.status.replicas==0) | .metadata.name' | xargs -I {} kubectl delete rs {} |
||
+ | <PRE> |
||
− | |||
+ | kubectl get --all-namespaces svc -o json | jq -r '.items[] | [.metadata.name,([.spec.ports[].nodePort | tostring ] | join("|"))] | @csv' |
||
− | Services |
||
+ | </PRE> |
||
− | |||
− | Get the self-link for a service using JSONPATH to format the output kubectl get svc heapster --namespace=kube-system -o=jsonpath={.metadata.selfLink} |
||
− | |||
− | Get 'service' external LB address kubectl get svc --namespace=kube-system -o=json | jq -r '.items[] | .status.loadBalancer.ingress[0]' |
||
− | |||
− | List all services in cluster and their nodePorts: kubectl get --all-namespaces svc -o json | jq -r '.items[] | [.metadata.name,([.spec.ports[].nodePort | tostring ] | join("|"))] | @csv' |
||
− | |||
− | Get Token for a service account & then get the secret |
||
+ | ===Get Token for a service account & then get the secret=== |
||
+ | <PRE> |
||
DEFAULT_TOKEN=$(kubectl --namespace=kube-system get serviceaccount default -o jsonpath="{.secrets[0].name}") |
DEFAULT_TOKEN=$(kubectl --namespace=kube-system get serviceaccount default -o jsonpath="{.secrets[0].name}") |
||
+ | </PRE> |
||
+ | <PRE> |
||
TOKEN_VALUE=$(kubectl --namespace=kube-system get secret "$DEFAULT_TOKEN" -o go-template="{{.data.token}}" | base64 -d) |
TOKEN_VALUE=$(kubectl --namespace=kube-system get secret "$DEFAULT_TOKEN" -o go-template="{{.data.token}}" | base64 -d) |
||
+ | </PRE> |
||
+ | ==curl== |
||
# Use it in a curl request to the api-server |
# Use it in a curl request to the api-server |
||
+ | <PRE> |
||
− | |||
curl -k -H "Authorization: Bearer $TOKEN_VALUE" https://10.0.1.212:6443/version |
curl -k -H "Authorization: Bearer $TOKEN_VALUE" https://10.0.1.212:6443/version |
||
curl -k -H "Authorization: Bearer $TOKEN_VALUE" https://localhost:6443/version |
curl -k -H "Authorization: Bearer $TOKEN_VALUE" https://localhost:6443/version |
||
+ | </PRE> |
||
− | Ingress |
||
+ | ==Ingress== |
||
− | List all ingresses hosts and paths: kubectl get --all-namespaces ing -o='custom-columns=NAME:.metadata.name,HOSTS:.spec.rules[*].host,PATHS:.spec.rules[*].http.paths[*].path' |
||
− | Persistent Volumes |
||
+ | List all ingresses hosts and paths |
||
− | List persistent volume claims in the elasticsearch namespace and for each print name & capacity kubectl get persistentvolumeclaims -n elasticsearch -o=jsonpath="{range .items[*]}{..name}{'\t'}{..capacity}{'\n'}{end}" |
||
+ | <PRE> |
||
+ | kubectl get --all-namespaces ing -o='custom-columns=NAME:.metadata.name,HOSTS:.spec.rules[*].host,PATHS:.spec.rules[*].http.paths[*].path' |
||
+ | </PRE> |
||
+ | |||
+ | ==Persistent Volumes== |
||
+ | |||
+ | List persistent volume claims in the elasticsearch namespace and for each print name & capacity |
||
+ | <PRE> |
||
+ | kubectl get persistentvolumeclaims -n elasticsearch -o=jsonpath="{range .items[*]}{..name}{'\t'}{..capacity}{'\n'}{end}" |
||
+ | </PRE> |
Текущая версия на 16:59, 19 февраля 2024
Шпаргалка по kubectl
много примеров тут: https://kubernetes.io/docs/reference/kubectl/quick-reference/
Частные случаи
--show-managed-fields
- посмотреть какие были операции с объектом
иногда помогает найти когда были работы с объектом, например меняли ли его недавно (может не работать с CRD)
kubectl -n kaas get secret iam-api-secrets --show-managed-fields -o yaml
Вывод переносов строк с -o jsonpath=
{"\n"}
kubectl get pods -A -o jsonpath='{range .items[*]}{.status.podIP}{"\n"}{end}'
Сортировка
kubectl get events --sort-by=.metadata.creationTimestamp
Поиск по полю
Скорее всего это все можно делать используя -o jsonpath
но я встречал неоднократные упоминания о багах, по-тому использую jq
простое условие
Получить только имя репликасетов у которых число реплик = 1
kubectl get rs -o json | jq -r '.items[] |select(.status.replicas==1) | .metadata.name'
Поиск специфичного объекта
Получить секрет(ы) у которых в аннотации в поле .metadata.annotations."lcm.mirantis.com/cluster-secret-type"
значение "kubeconfig"
(Пример специфичен для окружений определенного вида, но работает для любых объектов)
kubectl get secret -A -o json | jq ' .items[] | select(.metadata.annotations."lcm.mirantis.com/cluster-secret-type"=="kubeconfig") | .metadata.name'
Как писать такие запросы:
- Получить список, тут видно что все объекты помешены в List
.items[]
{ "apiVersion": "v1", "items": [ { "apiVersion": "v1", "kind": "Secret", "metadata": { "annotations": { "kubernetes.io/service-account.name": "default", "kubernetes.io/service-account.uid": "1ccf69fb-2f37-4684-bb16-19a8f20fd2fe" },
- Конструкция
jq '.items[] | <команда>'
проверяет каждый элемент списка, возвращая только соответствующие условию (в примере это условиеselect(.metadata.annotations."lcm.mirantis.com/cluster-secret-type"=="kubeconfig")
) .metadata.name
- вывести имя (но тут можно и содержимое или другое поле по желанию)
Nodes
Метки
kubectl get nodes --show-labels
Top usage
kubectl top nodes
Фильтрация вывода - все кроме
kubectl get node --selector='!node-role.kubernetes.io/master'
Без хедеров
kubectl get node --no-headers -o custom-columns=NAME:.metadata.name
Сортировка
kubectl get node --sort-by .metadata.creationTimestamp
Получение определенных полей с переименованием по аналогии с SELECT AS ..
kubectl get no -o json | jq -r '[.items[] | {name:.metadata.name, id:.spec.externalID, unschedulable:.spec.unschedulable}]'
[ ... { "name": "storage-3", "id": null, "unschedulable": null } ]
Простой просмотр утилизации
Это конечно хорошо бы улучшить
kubectl describe node | grep -A5 "Allocated"
Allocated resources: (Total limits may be over 100 percent, i.e., overcommitted.) Resource Requests Limits -------- -------- ------ cpu 1020m (8%) 4100m (34%) memory 1178Mi (0%) 3444Mi (2%)
Pods
Список контейнеров в поде
Для каждого контейнера pod-name, container-image container-name
Довольно коряво, конечно, но можно использовать как основу для своих скриптов
kubectl \ get pods \ -n osh-system \ --selector=app.kubernetes.io/instance=openstack-operator \ -o=jsonpath='{range .items[*]}{"\nStart output for POD: "}{.metadata.name}{"\nContaines:\n"}{range .spec.containers[*]}{.image}{"\t"}{.name}{"\n"}{end}{"End output for POD: "}{.metadata.name}{"\n"}{end}'
Пример вывода:
Start output for POD: openstack-controller-7896bc6d4d-l5mrz Containes: 127.0.0.1:44301/openstack/openstack-controller:0.14.18 osdpl 127.0.0.1:44301/openstack/openstack-controller:0.14.18 secrets 127.0.0.1:44301/openstack/openstack-controller:0.14.18 health 127.0.0.1:44301/openstack/openstack-controller:0.14.18 node 127.0.0.1:44301/openstack/openstack-controller:0.14.18 nodemaintenancerequest 127.0.0.1:44301/openstack/openstack-controller:0.14.18 ceph-secrets 127.0.0.1:44301/openstack/openstack-controller:0.14.18 osdplstatus 127.0.0.1:44301/openstack/openstack-controller:0.14.18 osdplsecret 127.0.0.1:44301/openstack/openstack-controller:0.14.18 tf-secrets End output for POD: openstack-controller-7896bc6d4d-l5mrz Start output for POD: openstack-controller-admission-5d78bf4d84-jmghf Containes: 127.0.0.1:44301/openstack/openstack-controller:0.14.18 openstack-operator End output for POD: openstack-controller-admission-5d78bf4d84-jmghf Start output for POD: openstack-controller-exporter-9f775b56f-gnntj Containes: 127.0.0.1:44301/openstack/openstack-controller:0.14.18 exporter End output for POD: openstack-controller-exporter-9f775b56f-gnntj
Найти все поды по метке (-l
) и вернуть список имеджей
kubectl get pods --all-namespaces -o=jsonpath='{..image}' -l app=prometheus
Число Pod на node
kubectl get pod --all-namespaces -o json | jq '.items | group_by(.spec.nodeName) | map({"nodeName": .[0].spec.nodeName, "count": length}) | sort_by(.count)'
Пример результата
[ ... { "nodeName": "os-control-1", "count": 55 }, { "nodeName": "os-control-3", "count": 70 } ]
Список запущенных и не запущенных POD
kubectl get pods --all-namespaces --field-selector=status.phase=Running
NAMESPACE NAME READY STATUS RESTARTS AGE ceph-lcm-mirantis ceph-controller-567884bc4f-h6ppp 2/2 Running 0 4d1h ceph-lcm-mirantis ceph-disk-daemon-22cl2 1/1 Running 1 (4d17h ago) 26d ceph-lcm-mirantis ceph-disk-daemon-gcsnz 1/1 Running 1 (4d17h ago) 26d ceph-lcm-mirantis ceph-disk-daemon-wwvrk 1/1 Running 1 (4d17h ago) 26d ceph-lcm-mirantis ceph-maintenance-controller-76669864dc-njppm 1/1 Running 0 4d1h ceph-lcm-mirantis ceph-request-controller-7d7d9ffc77-jz6lq 3/3 Running 0 4d1h ceph-lcm-mirantis ceph-status-controller-556574b56b-bgh78 1/1 Running 0 4d1h kaas client-certificate-controller-59546996f-dqmhf 1/1 Running 0 4d1h ...
kubectl get pods --all-namespaces --field-selector='status.phase!=Running
NAMESPACE NAME READY STATUS RESTARTS AGE openstack aodh-db-purge-28472041-2plwc 0/1 Completed 0 6h24m openstack aodh-ks-user-pznnt 0/1 Completed 0 4d2h openstack barbican-db-purge-28471921-st487 0/1 Completed 0 8h openstack barbican-ks-user-k9c8s 0/1 Completed 0 4d2h openstack ceilometer-ks-user-kh7mh 0/1 Completed 0 4d2h ...
Get all pods in All-namespaces, return mem and cpu (FOR EACH POD!)
kubectl get po -n elasticsearch --selector=service=elasticsearch-data -o=jsonpath="{range .items[*]}{.metadata.namespace}:{.metadata.name}{'\n'}{range .spec.containers[*]} {.resources.requests.cpu}{'\t'}{end}{'\n'}{end}"
Get the external IPs of PODs
kubectl get nodes --all-namespaces -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'
Show the images and their versions for each pod
kubectl get pods --all-namespaces -o jsonpath="{..image}" | tr -s '[[:space:]]' '\n' | sort | uniq -c kubectl get pods --all-namespaces -o jsonpath="{.items[*].spec.containers[*].image}" kubectl get pods -n default --field-selector=status.phase=Running --selector=app=my-service -o jsonpath="{..image}" | tr -s '[[:space:]]' '\n' | sort | uniq -c
Delete terminated/evicted pods
kubectl get po --selector=app=devops-logstash-service --field-selector=status.phase=Failed --no-headers -n elasticsearch | awk '{ print $1 }' | xargs -I {} kubectl delete po -n elasticsearch {}
Deployments
Get deployments, output as JSON, format output with JQ
kubectl get deployment --namespace=kube-system -o=json | jq '.items[].metadata.labels'
Get K8S Deployments matching the selector (look for key k8s-app with value heapster)
kubectl get deployment --all-namespaces --selector=k8s-app=heapster kubectl get svc --namespace=kube-system --selector=name=tiller
Scale a deployment
kubectl scale -n kube-system --replicas=0 'deployments/kube-dns' kubectl scale -n kube-system --replicas=2 'deployments/kube-dns'
Export the YAML file of a deployment (for reuse, modification, etc,.)
kubectl get deployments ghost --export -n ghost -o yaml > ghost.yaml
Replicasets
Get all replicasets sorted by the number of replicas
kubectl get rs -n elasticsearch --sort-by='.spec.replicas'
Get all replicasets where replicas==0 in a specific namespace
kubectl get rs -n elasticsearch -o json | jq -r '.items[] |select(.status.replicas==0) | .metadata.name'
Delete all replicasets that equal 0 in a specific namespace
kubectl get rs -n elasticsearch -o json | jq -r '.items[] |select(.status.replicas==0) | .metadata.name' | xargs -I {} kubectl delete rs {}
Services
Get the self-link for a service using JSONPATH to format the output
kubectl get svc heapster --namespace=kube-system -o=jsonpath={.metadata.selfLink}
Get 'service' external LB address
kubectl get svc --namespace=kube-system -o=json | jq -r '.items[] | .status.loadBalancer.ingress[0]'
List all services in cluster and their nodePorts
kubectl get --all-namespaces svc -o json | jq -r '.items[] | [.metadata.name,([.spec.ports[].nodePort | tostring ] | join("|"))] | @csv'
Get Token for a service account & then get the secret
DEFAULT_TOKEN=$(kubectl --namespace=kube-system get serviceaccount default -o jsonpath="{.secrets[0].name}")
TOKEN_VALUE=$(kubectl --namespace=kube-system get secret "$DEFAULT_TOKEN" -o go-template="{{.data.token}}" | base64 -d)
curl
- Use it in a curl request to the api-server
curl -k -H "Authorization: Bearer $TOKEN_VALUE" https://10.0.1.212:6443/version curl -k -H "Authorization: Bearer $TOKEN_VALUE" https://localhost:6443/version
Ingress
List all ingresses hosts and paths
kubectl get --all-namespaces ing -o='custom-columns=NAME:.metadata.name,HOSTS:.spec.rules[*].host,PATHS:.spec.rules[*].http.paths[*].path'
Persistent Volumes
List persistent volume claims in the elasticsearch namespace and for each print name & capacity
kubectl get persistentvolumeclaims -n elasticsearch -o=jsonpath="{range .items[*]}{..name}{'\t'}{..capacity}{'\n'}{end}"