https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
curl -LO https://dl.k8s.io/release/v1.32.0/bin/linux/amd64/kubectl
chmod +x kubectl
mkdir -p ~/.local/bin
mv ./kubectl ~/.local/bin/kubectl
echo 'alias k=kubectl' >> ~/.bashrc ;
echo 'source <(kubectl completion bash)' >> ~/.bashrc ;
echo 'complete -F __start_kubectl k' >> ~/.bashrc ;
echo 'source <(kubectl completion bash | sed 's/kubectl/k/g')' >> ~/.bashrc ;
echo "source <(kubectl completion bash | sed 's|__start_kubectl kubectl|__start_kubectl ks|g')" >> ~/.bashrc
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{":\t"}{"REQUESTS: "}{.spec.containers[0].resources.requests}{":\t"}{"LIMITS: "}{.spec.containers[0].resources.limits}{"\n"}{end}'
kubectl get pods -o wide --all-namespaces | awk '{print $8}' | sort | uniq -c
kubectl get node <node_name> -ojsonpath='{.status.capacity.pods}{"\n"}'
kubectl exec -it --namespace=<NAMESPACE> <pod> -- bash (-c "mongo")
pod=$(kubectl get pods --selector="name=frontend" --output=jsonpath={.items..metadata.name})
kubectl describe pod $pod
kubectl get pods --no-headers -o custom-columns=":metadata.name"
kubectl get deploy --no-headers -o custom-columns=":metadata.name"
kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'
kubectl get pods --sort-by=.metadata.creationTimestamp
kubectl get pods -A -o custom-columns=NAMESPACE:.metadata.namespace,POD:.metadata.name,STATUS:.status.phase,CONTAINERS:.spec.containers[*].name | grep -v 'Running'
kubectl get pods -o custom-columns="NAMESPACE:.metadata.namespace,POD:.metadata.name,CONTAINER:.spec.containers[*].name"
kubectl get pods --all-namespaces -o custom-columns="NAMESPACE:.metadata.namespace,POD:.metadata.name,CONTAINER:.spec.containers[*].name"
kubectl get pods -o=jsonpath='{range .items[*]}{"\n"}{.metadata.name}{":\t"}{range .status.containerStatuses[*]}{.name}{": "}{.ready}{", "}{end}{end}'
kubectl get pod --all-s | awk '{print $3}' | awk -F/ '{s+=$1} END {print s}' ### count
kubectl get pods --all -o wide --field-selector spec.nodeName=
kubectl get pods --all-namespaces -o wide --field-selector spec.nodeName=ocp2-produzione-g79jm-infra-0-2lw65
kubectl get pods --all-s --no-headers -o custom-columns=":.metadata." | sort | uniq -c | awk '{print ": "$2, "Pods: "$1}'
kubectl get pods --all-s -o=custom-columns=NAME:.metadata.name,:.metadata.
kubectl get po -o wide --sort-by=.spec.nodeName
kubectl get pods --all-namespaces -o=json | jq -c '.items[] | {name: .metadata.name, namespace: .metadata.namespace, claimName: .spec | select(has("volumes")).volumes[] | select(has("persistentVolumeClaim")).persistentVolumeClaim.claimName} | select(.claimName != null)'
kubectl get pods --all-namespaces -o custom-columns='POD_NAME:.metadata.name,NAMESPACE:.metadata.namespace,CLAIM_NAME:.spec.volumes[*].persistentVolumeClaim.claimName' | grep -v '<none>'
kubectl get pv -o custom-columns='NAME:.metadata.name,SERVER:.spec.nfs.server' | sort | uniq
kubectl get pv -o custom-columns='PV_NAME:.metadata.name,NFS_SERVER:.spec.nfs.server,PATH:.spec.nfs.path'
kubectl get pvc --all-namespaces -o json | jq -r --argjson pvs "$(kubectl get pv -o json | jq '.items')" '
($pvs | map({key: .metadata.name, value: .}) | from_entries) as $pvmap
| def nz($s): (if ($s // "") | tostring | length > 0 then $s else "-" end);
"NAMESPACE\tPVC\tSTATUS\tPV\tSTORAGECLASS\tACCESSMODES",
(.items[] as $pvc
| select( (($pvc.metadata.namespace // "") | startswith("openshift-")) | not )
| ($pvmap[$pvc.spec.volumeName] // null) as $pv
| [
nz($pvc.metadata.namespace),
nz($pvc.metadata.name),
nz($pvc.status.phase),
nz($pvc.spec.volumeName),
nz($pvc.spec.storageClassName // ($pv.spec.storageClassName // "")),
nz(
( ($pvc.spec.accessModes // []) | join(",") )
| if length > 0 then .
else ( ($pv.spec.accessModes // []) | join(",") )
end
)
] | @tsv
)
' | column -t
kubectl get pod PODNAME -o jsonpath='{range .status.containerStatuses[*]}{"Container: "}{.name}{"\n State: "}{.state.waiting.reason}{"\n Last State: "}{.lastState.terminated.reason}{"\n\n"}{end}'
kubectl get pod PODNAME -o go-template="{{range .status.containerStatuses}}{{.lastState.terminated.message}}{{end}}"
kubectl delete pod --field-selector=status.phase==Succeeded --all-namespaces
kubectl get pods --all-namespaces | awk '{if ($4 == "Completed") system ("kubectl delete pod " $2 " -n " $1 )}'
kubectl get po -A --sort-by=.metadata.creationTimestamp | grep -vE 'Completed|Running'
oc delete pod --field-selector=status.phase==Failed --all-namespaces
oc delete pod --field-selector=status.phase==Pending --all-namespaces
oc delete pod --field-selector=status.phase==Evicted --all-namespaces
oc get pods --all-namespaces | awk '{if ($4 != "Running") system ("oc delete pod " $2 " -n " $1 )}'
for POD in $(kubectl get pods|grep Evicted|awk '{print $1}'); do kubectl delete pods $POD ; done
kubectl get po -A --all-namespaces -o json | jq '.items[] | select(.status.reason!=null) | select(.status.reason | contains("Evicted")) | "kubectl delete po \(.metadata.name) -n \(.metadata.)"' | xargs -n 1 bash -c
kubectl get pods --all-namespaces | awk '$4=="Terminating" {print "kubectl delete pod --force --grace-period=0 --="$1" "$2}'
k logs -f NOMEPOD --tail=10
k logs -f NOMEPOD --since=30m
kubectl get pod -A -o json | jq '.items##### ##### | select(.status.reason=="Evicted") | {NAME:.metadata.name, :.metadata., REASON:.status.reason, MESSAGE:.status.message}'
Produce ENV for all pods, assuming you have a default container for the pods, default and the env command is supported. Helpful when running any supported command across all pods, not just env
for pod in $(kubectl get po --output=jsonpath={.items..metadata.name}); do echo $pod && kubectl exec -it $pod -- env; done
kubectl get pod/nginx -n default -o=custom-columns='IMAGE:spec.containers[*].image'
kubectl patch pod nginx -p '{"spec":{"containers":[{"name": "nginx","image": "nginx:1.9.6"}]}}'
kubectl patch pod myapp --patch '{"spec": {"containers": [{"name": "myapp-container", "resources": {"requests": {"cpu": "400m"}, "limits": {"cpu": "800m"}}}]}}'
kubectl patch pod myapp --patch '{"spec": {"containers": [{"name": "myapp-container", "resources": {"requests": {"memory": "1Gi"}}}]}}'
oc patch pod resizeme -p ' {"spec": {"containers": [{"name": "resizeme", "resources": { "requests" :{ "cpu" : 2, "memory": "512Mi"}, "limits" :{ "cpu" : 2, "memory" : "1Gi" } } }] }}'
kubectl get pod -o custom-columns="POD-NAME":.metadata.name,"":.metadata.,"CONTAINER-IMAGES":.spec.containers[*].image
#oc get pod -o custom-columns="POD-NAME":.metadata.name,"":.metadata.,"NODE":.spec.nodeName
kubectl logs my-pod
kubectl logs -l name=myLabel
kubectl logs my-pod --previous
kubectl logs my-pod -c my-container
kubectl logs -l name=myLabel -c my-container
kubectl logs my-pod -c my-container --previous
kubectl logs -f my-pod
kubectl logs -f my-pod -c my-container
kubectl logs -f -l name=myLabel --all-containers
kubectl run -i --tty busybox --image=busybox:1.28 -- sh
kubectl run nginx --image=nginx -n my
kubectl run nginx --image=nginx --dry-run=client -o yaml > pod.yaml
kubectl attach my-pod -i
kubectl port-forward my-pod 5000:6000
kubectl exec my-pod -- ls /
kubectl exec --stdin --tty my-pod -- /bin/sh
kubectl exec my-pod -c my-container -- ls /
kubectl top pod POD_NAME --containers
kubectl top pod POD_NAME --sort-by=cpu
kubectl top pod POD_NAME --sort-by=memory
kubectl cp /tmp/foo_dir my-pod:/tmp/bar_dir
kubectl cp /tmp/foo my-pod:/tmp/bar -c my-container
kubectl cp /tmp/foo my-/my-pod:/tmp/bar
kubectl cp my-namespace/my-pod:/tmp/foo /tmp/bar
kubectl logs mypod --since-time=2023-05-02T07:00:00Z --tail=100
kubectl logs <nome_pod> --timestamps | awk '/^[[:space:]]*[0-9]{4}-[0-9]{2}-[0-9]{2} 10:1[5-9]:|10:2[0-9]:/ {print}'
KUBECONFIG=~/.kube/config:~/.kube/kubconfig2
kubectl config view
kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}'
kubectl config view -o jsonpath='{.users[].name}' # display the first user
kubectl config view -o jsonpath='{.users[*].name}' # get a list of users
kubectl config get-contexts # display list of contexts
kubectl config current-context # display the current-context
kubectl config use-context my-cluster-name # set the default context to my-cluster-name
kubectl config set-cluster my-cluster-name # set a cluster entry in the kubeconfig
kubectl config set-cluster my-cluster-name --proxy-url=my-proxy-url
kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword
kubectl config set-context --current --namespace=ggckad-s2
kubectl config set-context gce --user=cluster-admin --namespace=foo \
&& kubectl config use-context gce
kubectl config unset users.foo # delete user foo
short alias to set/show context/namespace (only works for bash and bash-compatible shells, current context to be set before using kn to set namespace)
alias kx='f() { [ "$1" ] && kubectl config use-context $1 || kubectl config current-context ; } ; f'
alias kn='f() { [ "$1" ] && kubectl config set-context --current --namespace $1 || kubectl config view --minify | grep namespace | cut -d" " -f6 ; } ; f'
kubectl config set-context $(kubectl config current-context) --namespace=<namespace>
kubectl config view | grep namespace
kubectl get pods
kubectl api-resources --verbs=list --namespaced -o name | xargs -n 1 kubectl get --show-kind --ignore-not-found -n tibco-prod
kubectl api-resources --verbs=list --namespaced=true | awk '{ print $1 }' | xargs -n 1 kubectl get -n default
kubectl get quota --all-namespaces -o=custom-columns=Project:.metadata.namespace,TotalPods:.status.used.pods,TotalCPURequest:.status.used.requests'\.'cpu,TotalCPULimits:.status.used.limits'\.'cpu,TotalMemoryRequest:.status.used.requests'\.'memory,TotalMemoryLimit:.status.used.limits'\.'memory
kubectl get ns -L kubernetes.io/metadata.name
kubectl get events --sort-by=.metadata.creationTimestamp
kubectl get events --sort-by='.lastTimestamp' |
kubectl get events --all-namespaces --field-selector type=Warning
kubectl get events --sort-by=.metadata.creationTimestamp
kubectl get events -A --field-selector reason=OOMKilled --sort-by=.lastTimestamp
k rollout restart deployment ncp-3ds
kubectl set image deployment/application app-container=$IMAGE
kubectl patch deployment NOMEDEPLOY -p "{\"spec\":{\"template\":{\"metadata\":{\"annotations\":{\"date\":\"`date +'%s'`\"}}}}}"
kubectl set env deploy/<DEPLOY> MYVAR=$(date)
kubectl get deployments --all-namespaces | tail +2 | awk '{ cmd=sprintf("kubectl rollout restart deployment -n %s %s", $1, $2) ; system(cmd) }'
kubectl get deployments -n 2a-cil -o custom-columns=NAME:.metadata.name|grep -iv NAME|while read LINE; do kubectl rollout restart deployment $LINE -n 2a-cil ; done
cat all_deployment.txt | grep -v "0/0" | grep -v NAME | grep -v kube-system | grep -v istio-system | while read ns dep more ; do kubectl scale deployment $dep -n $ns --replicas=0; done
cat all_deployment.txt | grep -v "0/0" | grep -v NAME | grep -v istio-system | grep -v kube-system | while read ns dep rep more; do replica=$(echo $rep | cut -f2 -d "/"); kubectl scale deployment $dep -n $ns --replicas=$replica; done
replica_spec=$(kubectl get deployment/applicatiom -o jsonpath='{.spec.replicas}')
kubectl scale --replicas=0 deployment application
kubectl scale --replicas=$replica_spec deployment application
for i in $(kubectl get deployments --no-headers -o custom-columns=":metadata.name"); do k get deploy $i -o yaml > $i-deploy.yaml; done
kubectl set resources deployment nginx --limits cpu=200m,memory=512Mi --requests cpu=100m,memory=256Mi
kubectl set resources deployment nginx --limits cpu=0,memory=0 --requests cpu=0,memory=0
kubectl patch deployment velero -n velero --patch \
'{"spec":{"template":{"spec":{"containers":[{"name": "velero", "resources": {"limits":{"cpu": "1", "memory": "512Mi"}, "requests": {"cpu": "1", "memory": "128Mi"}}}]}}}}'
kubectl rollout status deployment nginx
kubectl rollout pause deployment nginx
kubectl rollout resume deployment nginx
kubectl rollout history deployment nginx
kubectl rollout undo deployments nginx (--to-revision 3)
kubectl patch deployment valid-deployment --type json -p='[{"op": "remove", "path": "/spec/template/spec/containers/0/livenessProbe"}]'
kubectl get deployments -o name | sed -e 's/.*\///g' | xargs -I {} kubectl patch deployment {} --type=json -p='[{"op": "replace", "path": "/spec/template/spec/containers/0/imagePullPolicy", "value": "IfNotPresent"}]'
kubectl patch deployment my-deployment -p '{"spec":{"template":{"spec":{"imagePullSecrets":[{"name":"my-secret-pull"}]}}}}'
kubectl get deployments -n <NAMESPACE> -o custom-columns=NAME:.metadata.name|grep -iv NAME|while read LINE; do kubectl rollout restart deployment $LINE -n <NameSpace Name> ; done;
kubectl rollout restart deployment -n <NAMESPACE>
for deployment_name in $deployment_names; do
container_names=$(kubectl get deployment $deployment_name -o=jsonpath='{.spec.template.spec.containers[*].name}')
for container_name in $container_names; do
image=$(kubectl get deployment $deployment_name -o=jsonpath="{.spec.template.spec.containers[?(@.name=='$container_name')].image}")
echo "Deployment: $deployment_name - Container: $container_name - Immagine: $image"
done
done
kubectl get deploy -n <NAMESPACE> -o custom-columns=\
"NAME:.metadata.name,\
LABELS:.metadata.labels,\
NODESELECTOR:.spec.template.spec.nodeSelector"
echo -e "DEPLOYMENT\tNAMESPACE\tPVC_NAME\tREPLICAS"
kubectl get deploy --all-namespaces -o json | jq -r '
.items[] |
{
name: .metadata.name,
namespace: .metadata.namespace,
replicas: (.spec.replicas // 1),
pvc_names: (
.spec.template.spec.volumes[]?
| select(.persistentVolumeClaim != null)
| .persistentVolumeClaim.claimName
)
} |
select(.pvc_names != null) |
"\(.name)\t\(.namespace)\t\(.pvc_names)\t\(.replicas)"
'
kubectl run newpod --image image1 --overrides='{ "spec": { "affinity": { "nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [{ "matchExpressions": [{ "key": "kubernetes.io/hostname", "operator": "In", "values": [ "one-worker-node", "second-worker-node" ]} ]} ]} } } } }'
kubectl label nodes grpi-kb1-kv21 app=invydio
kubectl label node <nome-nodo> node-role.kubernetes.io/worker=worker
kubectl label nodes --all -app=invydio
kubectl label nodes --all app-
kubectl patch deployment my-deployment -p '{"spec":{"template":{"spec":{"nodeSelector":{"app":"apphub"}}}}}'
kubectl patch deployment my-deployment -p '{"spec":{"template":{"spec":{"nodeSelector":{"node-role.kubernetes.io/worker":"true"}}}}}'
kubectl patch deployment <nome-del-tuo-deployment> --type='json' -p='[{"op": "remove", "path": "/spec/template/spec/nodeSelector/node-role.kubernetes.io~1worker"}]'
kubectl patch deployment <nome-del-tuo-deployment> --type='json' -p='[{"op": "replace", "path": "/spec/template/spec/nodeSelector", "value": {"app": "apphub"}}]'
kubectl get deployment my-deployment -o jsonpath={.spec.template.spec.nodeSelector}
stampare_valore_label_pod() { namespace=$(kubectl config view --minify --output 'jsonpath={..namespace}')
kubectl get pods --namespace=$namespace -o=jsonpath='{range .items[*]}{"Namespace: "}{.metadata.namespace}{"\nPod Name: "}{.metadata.name}{"\nLabel: "}{.metadata.labels}{"\n\n"}'
}
read -p "Inserisci la label nel formato label:valore: " label
label_key=$(echo
kubectl get pods --namespace=$(kubectl config view --minify --output 'jsonpath={..namespace}') -l "$label_key"="$label_value" -o wide
kubectl get deployments --namespace=$(kubectl config view --minify --output 'jsonpath={..namespace}') -o=jsonpath='{range .items[*]}{"\n\nDeployment Name: "}{.metadata.name}{"\nNamespace: "}{.metadata.namespace}{"\nNodeSelector: "}{.spec.template.spec.nodeSelector}{"\n"}'
declare -A cpu_used mem_used
while read -r name cpu mem; do
cpu_used[$name]="${cpu%m}m"
mem_used[$name]="${mem%Mi}Mi"
done < <(kubectl top nodes --no-headers 2>/dev/null | awk '{print $1, $2, $3}')
(
echo -e "NAME\tROLE\tCPU_CAPACITY\tCPU_ALLOCATABLE\tCPU_USED\tMEM_CAPACITY\tMEM_ALLOCATABLE\tMEM_USED"
kubectl get nodes -o json | jq -r '
.items[] |
[
.metadata.name,
(.metadata.labels | to_entries | map(select(.key | startswith("node-role.kubernetes.io/"))) | map(.key | sub("node-role.kubernetes.io/"; "")) | join(",")),
(if (.status.capacity.cpu | test("m$")) then .status.capacity.cpu else ((.status.capacity.cpu|tonumber)*1000|tostring)+"m" end),
(if (.status.allocatable.cpu | test("m$")) then .status.allocatable.cpu else ((.status.allocatable.cpu|tonumber)*1000|tostring)+"m" end),
(.status.capacity.memory | capture("(?<num>[0-9]+)(?<unit>[KMG]i)?") | .num as $n | .unit as $u |
if $u=="Ki" then ($n|tonumber)/1024
elif $u=="Mi" then ($n|tonumber)
elif $u=="Gi" then ($n|tonumber)*1024
else ($n|tonumber)/1024 end | floor | tostring),
(.status.allocatable.memory | capture("(?<num>[0-9]+)(?<unit>[KMG]i)?") | .num as $n | .unit as $u |
if $u=="Ki" then ($n|tonumber)/1024
elif $u=="Mi" then ($n|tonumber)
elif $u=="Gi" then ($n|tonumber)*1024
else ($n|tonumber)/1024 end | floor | tostring)
] |
@tsv
' | while IFS=$'\t' read -r name role cpu_cap cpu_alloc mem_cap mem_alloc; do
[[ "$role" != *worker* ]] && continue
# Aggiunge suffissi se mancanti
[[ "$cpu_cap" != *m ]] && cpu_cap="${cpu_cap}m"
[[ "$cpu_alloc" != *m ]] && cpu_alloc="${cpu_alloc}m"
[[ "$mem_cap" != *Mi ]] && mem_cap="${mem_cap}Mi"
[[ "$mem_alloc" != *Mi ]] && mem_alloc="${mem_alloc}Mi"
echo -e "$name\t$role\t$cpu_cap\t$cpu_alloc\t${cpu_used[$name]:-N/A}\t$mem_cap\t$mem_alloc\t${mem_used[$name]:-N/A}"
done
) | column -t
alias util='kubectl get nodes --no-headers | awk '\''{print $1}'\'' | xargs -I {} sh -c '\''echo {} ; kubectl describe node {} | grep Allocated -A 5 | grep -ve Event -ve Allocated -ve percent -ve -- ; echo '\'''
util
kubectl node <node-name> kubernets.io/role=<name-your-node-role> ##### --overwrite #####
es. kubectl label node worker1 node-role.kubernetes.io/worker=worker
kubectl patch deployments nginx-deployment -p '{"spec": {"template": {"spec": {"nodeSelector": {"kubernetes.io/hostname": "node-2"}}}}}'
kubectl get nodes <NODE> -o json | jq -r '.spec.taints | .[]'
kubectl get nodes -o custom-columns="Name:.metadata.name,InternalIP:.status.addresses[0].address"
kubectl get nodes -o custom-columns="Name:.metadata.name,InternalIP:.status.addresses[0].address,Kernel:.status.nodeInfo.kernelVersion,MemoryPressure:.status.conditions[0].status,DiskPressure:.status.conditions[1].status,PIDPressure:.status.conditions[2].status,Ready:.status.conditions[3].status"
kubectl cordon my-node # Mark my-node as unschedulable
kubectl drain my-node # Drain my-node in preparation for maintenance
kubectl uncordon my-node # Mark my-node as schedulable
kubectl top node my-node # Show metrics for a given node
kubectl cluster-info # Display addresses of the master and services
kubectl cluster-info dump # Dump current cluster state to stdout
kubectl cluster-info dump --output-directory=/path/to/cluster-state # Dump current cluster state to /path/to/cluster-state
kubectl get nodes -o=custom-columns=NodeName:.metadata.name,TaintKey:.spec.taints[*].key,TaintValue:.spec.taints[*].value,TaintEffect:.spec.taints[*].effect
kubectl taint nodes foo dedicated=special-user:NoSchedule
kubectl patch svc prometheus-grafana --type='json' -p '[{"op":"replace","path":"/spec/type","value":"NodePort"}]' -n kube-prometheus-stack
kubectl patch svc prometheus-grafana --type='json' -p '[{"op": "add", "path":"/spec/ports/0/nodePort", "value":33333}]' -n kube-prometheus-stack
kubectl patch service prometheus-kube-prometheus-prometheus -n kube-prometheus-stack -p '{"spec": {"type": "ClusterIP"}}'
#!/bin/bash
current_ns=$(kubectl config view --minify --output 'jsonpath={..namespace}')
current_ns=${current_ns:-default} # se non c'è namespace, usa default
echo "Namespace: $current_ns"
echo "Deployment -> Labels -> Service(s) matching"
echo "------------------------------------------------"
for deploy in $(kubectl get deploy -n $current_ns -o jsonpath='{.items[*].metadata.name}'); do
labels=$(kubectl get deploy $deploy -n $current_ns -o json | jq -r '.spec.template.metadata.labels | to_entries | map("\(.key)=\(.value)") | join(", ")')
echo "Deployment: $deploy"
echo " Labels: $labels"
for svc in $(kubectl get svc -n $current_ns -o jsonpath='{.items[*].metadata.name}'); do
svc_selector=$(kubectl get svc $svc -n $current_ns -o json | jq -r '.spec.selector // {} | to_entries | map("\(.key)=\(.value)") | join(", ")')
if [ -n "$svc_selector" ]; then
match=1
for label in $(echo $svc_selector | tr ', ' '\n'); do
if ! echo $labels | grep -q "$label"; then
match=0
break
fi
done
if [ $match -eq 1 ]; then
echo " -> Service matching: $svc"
fi
fi
done
echo ""
done
kubectl get cronjob -n offloading
kubectl create job --from=cronjob/<cronjob-name> <job-name> -n offloading
kubectl get pods -n offloading
kubectl delete job <job-name>
kubectl delete pods/nomepod -n offloading
kubectl patch cronjobs <job-name> -p '{"spec" : {"suspend" : true }}'
kubectl get cronjob | grep False | awk '{print $1}' | xargs kubectl patch cronjob -p '{"spec" : {"suspend" : true }}'
kubectl get cronjob | grep True | awk '{print $1}' | xargs kubectl patch cronjob -p '{"spec" : {"suspend" : false }}'
for CJ in $(k get cj -A | grep ocr | awk '{print $2}'); do k patch cj $CJ -p '{"spec" : {"suspend" : true }}'; done
for CJ in $(k get cj -A | grep ocr | awk '{print $2}'); do k patch cj $CJ -p '{"spec" : {"suspend" : false }}'; done
for CJ in $(k get cj -A | grep ocr | awk '{print $2}'); do k get cj $CJ -o yaml > $CJ.backup.yaml; done
for CJ in $(k get cj -A | grep ocr | awk '{print $2}'); do k delete cj $CJ ; done
for CJ in $(ls -1 *.yaml); do k create -f $CJ.backup.yaml ; done
kubectl create job hello --image=busybox:1.28 -- echo "Hello World"
kubectl create cronjob hello --image=busybox:1.28 --schedule="*/1 * * * *" -- echo "Hello World"
kubectl get pods -o jsonpath='{range .items[*]}{"\n"}{.metadata.name}{":\t"}{range .spec.containers[*]}{.image}{", "}{end}{end}' | sort
kubectl get pods -o jsonpath="{.items[*].spec.containers[*].image}"
kubectl annotate ingress pacman-ingress -n pacman kubernetes.io/ingress.class="nginx-default" --overwrite
kubectl annotate ingress pacman-ingress -n pacman nginx.ingress.kubernetes.io/rewrite-target=/
kubectl -n <namespace> patch daemonset <name-of-daemon-set> -p '{"spec": {"template": {"spec": {"nodeSelector": {"non-existing": "true"}}}}}'
kubectl -n <namespace> patch daemonset <name-of-daemon-set> --type json -p='[{"op": "remove", "path": "/spec/template/spec/nodeSelector/non-existing"}]'
kubectl get secret my-secret -o 'go-template={{index .data "username"}}' | base64 -d
kubectl get secret my-secret -o json | jq '.data | map_values(@base64d)'
kubectl get secret my-secret -n my-namespace -o json | jq -r '.data | to_entries[] | "\(.key): \(.value | @base64d)"'
kubectl patch secret test --type='json' -p='[{"op" : "replace" ,"path" : "/data/username" ,"value" : "dGVzdHVzZXIy"}]'
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Secret
metadata:
name: mysecret
type: Opaque
data:
password: $(echo -n "s33msi4" | base64 -w0)
username: $(echo -n "jane" | base64 -w0)
EOF
kubectl get secret my-secret -o go-template='{{range $k,$v := .data}}{{"### "}}{{$k}}{{"\n"}}{{$v|base64decode}}{{"\n\n"}}{{end}}'
kubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniq
kubectl get cm <NOME-CONFIGMAP> -o jsonpath='{.data.ballerina\.conf}' > ballerina.conf
kubectl get cm 3-2-0-wso2apim-gw-worker-conf -o template='{{ index .data "deployment.toml" }}'
kubectl auth can-i '*' '*'
kubectl auth can-i create pods --all-namespaces
kubectl auth can-i list deployments.extensions
kubectl auth can-i get pods --as=system:serviceaccount:default:default
kubectl auth can-i --list
### set sc as default ###
kubectl patch storageclass nfs-client -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}' && kubectl patch storageclass local-path -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"false"}}}'
$newsize='{\"spec\":{\"resources\":{\"requests\":{\"storage\":\"<newsize>Gi\"}}}}'
kubectl patch pvc <name of PVC> --namespace <namespace> --type merge --patch $newsize
kubectl get pods -n ping -o go-template --template='{{range .items}}{{"pod: "}}{{.metadata.name}}
{{if .spec.securityContext}}
PodSecurityContext:
{{"runAsGroup: "}}{{.spec.securityContext.runAsGroup}}
{{"runAsNonRoot: "}}{{.spec.securityContext.runAsNonRoot}}
{{"runAsUser: "}}{{.spec.securityContext.runAsUser}} {{if .spec.securityContext.seLinuxOptions}}
{{"seLinuxOptions: "}}{{.spec.securityContext.seLinuxOptions}} {{end}}
{{else}}PodSecurity Context is not set
{{end}}{{range .spec.containers}}
{{"container name: "}}{{.name}}
{{"image: "}}{{.image}}{{if .securityContext}}
{{"allowPrivilegeEscalation: "}}{{.securityContext.allowPrivilegeEscalation}} {{if .securityContext.capabilities}}
{{"capabilities: "}}{{.securityContext.capabilities}} {{end}}
{{"privileged: "}}{{.securityContext.privileged}} {{if .securityContext.procMount}}
{{"procMount: "}}{{.securityContext.procMount}} {{end}}
{{"readOnlyRootFilesystem: "}}{{.securityContext.readOnlyRootFilesystem}}
{{"runAsGroup: "}}{{.securityContext.runAsGroup}}
{{"runAsNonRoot: "}}{{.securityContext.runAsNonRoot}}
{{"runAsUser: "}}{{.securityContext.runAsUser}} {{if .securityContext.seLinuxOptions}}
{{"seLinuxOptions: "}}{{.securityContext.seLinuxOptions}} {{end}}{{if .securityContext.windowsOptions}}
{{"windowsOptions: "}}{{.securityContext.windowsOptions}} {{end}}
{{else}}
SecurityContext is not set
{{end}}
{{end}}{{end}}'
kube-dump ns -d "$HOME/BACKUP-DR" -f -n "$(kubectl get ns -o jsonpath='{.items[*].metadata.name}' | tr ' ' '\n' | grep -Ev '^(openshift|kube)' | paste -sd, -)" -r deployments.apps,statefulsets.apps
kube-capacity -u -o json | jq -r '
[.nodes[] | {name, cpu_requests: .cpu.requests, cpu_limits: .cpu.limits, cpu_util: .cpu.utilization, memory_requests: .memory.requests, memory_limits: .memory.limits, memory_util: .memory.utilization}] |
(["NODE", "CPU REQUESTS", "CPU LIMITS", "CPU UTIL", "MEMORY REQUESTS", "MEMORY LIMITS", "MEMORY UTIL"]),
(.[] | [.name, .cpu_requests, .cpu_limits, .cpu_util, .memory_requests, .memory_limits, .memory_util])
| @csv
' > "$(oc cluster-info | grep 'Kubernetes control plane' | awk -F'/' '{print $3}' | awk -F':' '{print $1}')-node-capacity.csv"
kube-capacity -u -p -o json | jq -r '
(["NODE", "NAMESPACE", "POD", "CPU REQUESTS", "CPU REQUESTS %", "CPU LIMITS", "CPU LIMITS %", "CPU UTIL", "CPU UTIL %", "MEMORY REQUESTS", "MEMORY REQUESTS %", "MEMORY LIMITS", "MEMORY LIMITS %", "MEMORY UTIL", "MEMORY UTIL %"]),
(.nodes[] |
. as $node |
.pods[] |
[$node.name, .namespace, .name, .cpu.requests, .cpu.requestsPercent, .cpu.limits, .cpu.limitsPercent, .cpu.utilization, .cpu.utilizationPercent, .memory.requests, .memory.requestsPercent, .memory.limits, .memory.limitsPercent, .memory.utilization, .memory.utilizationPercent]) |
@csv' > "$(oc cluster-info | grep 'Kubernetes control plane' | awk -F'/' '{print $3}' | awk -F':' '{print $1}')-pod-capacity.csv"
kubectl get pod pod-name -ojsonpath='{.status.containerStatuses[0].containerID}'
docker inspect container-id | grep -i logpath
docker images --format 'table {{.Repository}}\t{{.ID}}\t{{.Tag}}\t{{.Size}}' | (read -r; printf "%s\n" "$REPLY"; sort -h -k7)
docker container ls --format "table {{.ID}}\t{{.Labels}}"
docker image ls -a --filter "not label=com.docker.ucp.version=3.5.3"
docker image prune --filter label!=com.docker.dtr.version: 2.9.7
docker image prune --filter label!=com.docker.ucp.version=3.5.3 --filter label!=com.docker.dtr.version:2.9.7
runningImages=$(docker ps --format {{.Image}})
docker images --format "{{.ID}} {{.Repository}}:{{.Tag}}" | grep -v "$runningImages"
docker ps --format "{{.Names}}" | while read name; do echo "$name: $(docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $name)"; done
mkdir /etc/systemd/system/docker.service.d ; cd /etc/systemd/system/docker.service.d
cat <<EOF > http-proxy.conf
[Service] Environment="HTTP_PROXY=http://user01:password@10.10.10.10:8080/" Environment="HTTPS_PROXY=https://user01:password@10.10.10.10:8080/" Environment="NO_PROXY= hostname.example.com,172.10.10.10" EOF
systemctl daemon-reload systemctl restart docker
systemctl show docker --property Environment
removecontainers() {
docker stop $(docker ps -aq)
docker rm $(docker ps -aq)
}
armageddon() { removecontainers
docker network prune -f
docker rmi -f $(docker images --filter dangling=true -qa)
docker volume rm $(docker volume ls --filter dangling=true -q)
docker rmi -f $(docker images -qa)
}
docker rmi $(docker images --format '{{.Repository}}:{{.Tag}}' | grep 'imagename')
docker rmi $(docker images --filter=reference="IMAGENAME:TAG")
docker inspect -f $'{{.Name}}\t{{.GraphDriver.Data.MergedDir}}' $(docker ps -aq)
kubectl get pods -o wide -n offloading-coll --field-selector spec.nodeName=grpi-kb1-kv31 -o json | jq -r '.items[].status.containerStatuses[].containerID' | tr -d 'docker://'```

