Skip to content

Instantly share code, notes, and snippets.

@orcunuso
Last active June 25, 2020 09:29
Show Gist options
  • Save orcunuso/03c5ca6537de531b9319cc154881f399 to your computer and use it in GitHub Desktop.
Save orcunuso/03c5ca6537de531b9319cc154881f399 to your computer and use it in GitHub Desktop.

My Cheat Sheet Related with Containers

As my daily routine highly includes Docker, Kubernetes and OpenShift, I thought that it would be a good idea to prepare and publish a cheat sheet for myself and also for anyone who might find this useful. So let's start with some aliases.

alias dockerauth='cat $HOME/.docker/config.json'
alias dockerps='docker ps --format "table {{.ID}}\t{{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Command}}" --no-trunc'
alias ocsource='source <(oc completion bash)'
alias ocnodelistpods='oc adm manage-node --list-pods'
alias ocnodemaintenanceon='oc adm manage-node --schedulable=false'
alias ocnodemaintenanceoff='oc adm manage-node --schedulable=true'
alias ocnodedrain='oc adm drain --delete-local-data --force --ignore-daemonsets --grace-period=120'

alias k='kubectl'
alias ksource='source <(kubectl completion bash)'
alias kpod='kubectl get pods -o wide --all-namespaces'
alias ksvc='kubectl get services -o wide --all-namespaces'
alias kdep='kubectl get deployments -o wide --all-namespaces'
alias kds='kubectl get daemonsets -o wide --all-namespaces'
alias king='kubectl get ingress -o wide --all-namespaces'
alias knode='kubectl get nodes -o wide'
alias kcreate='kubectl create -f'
alias kapply='kubectl apply -f'
alias kget='kubectl get -o wide'
alias kswitch='kubectl config use-context'
alias knamespace='kubectl config set-context `kubectl config current-context` --namespace'

Human-readable Commands

These are the commands that I call "human-readable" commands that does not include things like go-template or jsonpaths. The oc binary offers the same capabilities as the kubectl binary, but it is further extended to natively support OpenShift features. Hence, most commands can easily be adapted for native Kubernetes by just replacing oc with kubectl, and some needs a little bit more than that but still doable.

# Login with service account
oc login api-server --token=$(oc sa get-token sa -n namespace)

# Check RBAC policy for a user
oc auth can-i create namespace --as=user

# Taint a worker node
oc adm taint nodes workernode gpu=yes:NoSchedule

# Import Image
oc import-image netshoot:latest --from docker.io/orcunuso/netshoot:20200409 --confirm --insecure=true

# Update deployment config
oc patch dc dcname -p '{"spec":{"template":{"spec":{"securityContext":{"runAsUser": 1001}}}}}'

# Add egress IP to a namespace
oc patch netnamespace namespace -p '{"egressIPs": ["192.168.1.101"]}'

# List projects with labels in additional columns
oc get project -L serviceid -L cluster

# Create service with custom port
oc expose pod netshoot8514 --name=netshoot8514 --type=ClusterIP --external-ip=10.10.10.10 --port=8514 --protocol=UDP

# Create a new build with Dockerfile
oc new-build --name buildname python~<gitURL> --strategy docker --source-secret=secretname

# Create a new app from source
oc new-app '<imagestream>~<gitURL>#<branch>'

# Commands related with prune operations
oc adm prune deployments --orphans --keep-complete=10 --keep-failed=1 --keep-younger-than=60m --confirm
oc adm prune builds --orphans --keep-complete=10 --keep-failed=1 --keep-younger-than=60m --confirm
oc adm prune images --keep-tag-revisions=8 --keep-younger-than=60m --registry-url=<registryURL> --confirm

Less Human-readable Commands

The commands listed are intended to give an idea of usage of advanced filtering and formatting such as custom columns, jsonpath or go-template.

# Get a specific label within all projects
oc get project -o custom-columns=NAME:.metadata.name,SERVICEID:.metadata.labels.serviceid

# Run a pod on a tainted node
oc run netshoot --overrides='{"spec": {"nodeSelector": {"node-role.kubernetes.io/gpu": "true"}, "tolerations": [{"effect": "NoSchedule", "key": "node.kubernetes.io/memory-pressure", "operator": "Exists"}, {"effect": "NoSchedule", "key": "gpu", "operator": "Equal", "value": "yes"}]}}' --image=docker.io/orcunuso/netshoot:20200409 --restart=Never -l appname=netshoot -n namespace

# Run a pod with pvc
oc run netshoot --overrides='{"spec": {"containers": [{"image": "docker.io/orcunuso/netshoot:20200409", "name": "netshoot","volumeMounts": [{"mountPath": "/data","name": "voldata"}]}],"volumes": [{"name": "voldata","persistentVolumeClaim": {"claimName": "pvc01"}}]}}' --image=notused --restart=Never -l app=netshoot -n namespace

# Assign pod to a specific node
oc patch dc netshoot -p '{"spec":{"template":{"spec":{"nodeSelector":{"kubernetes.io/hostname": "workernode"}}}}}'

# Delete pods in an error state
for pod in $(oc get pods -n namespace | grep Error | awk '{print $1}'); do oc delete pod --grace-period=1 ${pod}; done
for pod in $(oc get pods --all-namespaces | grep Error | awk '{print $2}'); do oc delete pod --grace-period=1 ${pod}; done

# Get pods/nodes counts
oc get pods -o json --all-namespaces | jq '.items | group_by(.spec.nodeName) | map({"nodeName": .[0].spec.nodeName, "count": length}) | sort_by(.count)'

# Get pod cpu/memory resources in a namespace
oc get pods -o custom-columns=NAME:.metadata.name,CPU-REQUEST:.spec.containers[*].resources.requests.cpu,MEM-REQUEST:.spec.containers[*].resources.requests.memory,CPU-LIMIT:.spec.containers[*].resources.limits.cpu,MEM-LIMIT:.spec.containers[*].resources.limits.memory -n namespace

# Get running images in a namespace
oc get pods -o jsonpath='{range .items[*]}{"\n"}{.metadata.name}{":\t"}{range .spec.containers[*]}{.image}{", "}{end}{end}' -n namespace | sort

# Get running pods with go-template
oc get pods -o go-template='{{range .items}}{{if eq .status.phase "Running"}}{{.metadata.name}}{{"\t"}}{{.status.phase}}{{"@"}}{{.spec.nodeName}}{{"\n"}}{{end}}{{end}}'
oc get pods -o go-template --template='{{range .items}}{{if eq .status.phase "Running"}}Name: {{.metadata.name}}{{"\t"}}HostIP: {{.status.hostIP}}{{"\t"}}PodIP: {{.status.podIP}}{{"\n"}}{{end}}{{end}}{{"\n"}}'

# Get mounted volumes
oc get pods -o custom-columns=NAME:.metadata.name,VMOUNTS:.spec.containers[*].volumeMounts[*].mountPath

# Get worker nodes with jsonpath
oc get nodes -o jsonpath='{"NAME\t\t\t\tCREATION DATE\n"}{range .items[?(@.metadata.labels.node-role\.kubernetes\.io/compute=="true")]}{.metadata.name}{"\t"}{.metadata.creationTimestamp}{"\n"}{end}'

# Inspect a TLS certificate in a secret
oc get secret secretname -o json | jq -r .data[\"tls.crt\"] | base64 -d | openssl x509 -in /dev/stdin -text -noout

# Find out PVs with released PVCs
oc get pv -o jsonpath='{range.items[?(@.status.phase=="Released")]}{.metadata.name}{"\n"}{end}'

# LimitRanges in all namespaces
oc get limitrange --all-namespaces -o custom-columns=NAMESPACE:.metadata.namespace,CPU-REQ:.spec.limits[0].defaultRequest.cpu,CPU-LIM:.spec.limits[0].default.cpu,MEM-REQ:.spec.limits[0].defaultRequest.memory,MEM-LIM:.spec.limits[0].default.memory
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment