Skip to content

Commit 43fddd4

Browse files
authored
Merge pull request #1 from pierretou/pierretou-kubectl
Create kubectl.md sheetcheat
2 parents cb4e030 + 3a62431 commit 43fddd4

File tree

1 file changed

+366
-0
lines changed

1 file changed

+366
-0
lines changed

kubectl.md

Lines changed: 366 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,366 @@
1+
## Getting started
2+
3+
### Kubectl Autocomplete
4+
5+
#### BASH
6+
7+
```bash
8+
source <(kubectl completion bash) # active l'auto-complétion pour bash dans le shell courant, le paquet bash-completion devant être installé au préalable
9+
echo "source <(kubectl completion bash)" >> ~/.bashrc # ajoute l'auto-complétion de manière permanente à votre shell bash
10+
```
11+
12+
You can also use a shorthand alias for `kubectl` that also works with completion:
13+
14+
```bash
15+
alias k=kubectl
16+
complete -F __start_kubectl k
17+
```
18+
19+
#### ZSH
20+
21+
```zsh
22+
source <(kubectl completion zsh) # active l'auto-complétion pour zsh dans le shell courant
23+
echo "if [ $commands[kubectl] ]; then source <(kubectl completion zsh); fi" >> ~/.zshrc # ajoute l'auto-complétion de manière permanente à votre shell zsh
24+
```
25+
26+
### Kubectl Context and Configuration
27+
28+
Set which Kubernetes cluster `kubectl` communicates with and modifies configuration information. See [Authenticating Across Clusters](https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/) with kubeconfig documentation for detailed config file information.
29+
30+
```bash
31+
kubectl config view # Show Merged kubeconfig settings.
32+
33+
# use multiple kubeconfig files at the same time and view merged config
34+
KUBECONFIG=~/.kube/config:~/.kube/kubconfig2
35+
36+
kubectl config view
37+
38+
# get the password for the e2e user
39+
kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}'
40+
41+
kubectl config view -o jsonpath='{.users[].name}' # display the first user
42+
kubectl config view -o jsonpath='{.users[*].name}' # get a list of users
43+
kubectl config get-contexts # display list of contexts
44+
kubectl config current-context # display the current-context
45+
kubectl config use-context my-cluster-name # set the default context to my-cluster-name
46+
47+
# add a new user to your kubeconf that supports basic auth
48+
kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword
49+
50+
# permanently save the namespace for all subsequent kubectl commands in that context.
51+
kubectl config set-context --current --namespace=ggckad-s2
52+
53+
# set a context utilizing a specific username and namespace.
54+
kubectl config set-context gce --user=cluster-admin --namespace=foo \
55+
&& kubectl config use-context gce
56+
57+
kubectl config unset users.foo # delete user foo
58+
```
59+
60+
### Apply
61+
62+
`apply` manages applications through files defining Kubernetes resources. It creates and updates resources in a cluster through running `kubectl apply`. This is the recommended way of managing Kubernetes applications on production. See [Kubectl Book](https://kubectl.docs.kubernetes.io/).
63+
64+
### Creating Objects
65+
66+
Kubernetes manifests can be defined in YAML or JSON. The file extension `.yaml`, `.yml`, and `.json` can be used.
67+
68+
```bash
69+
kubectl apply -f ./my-manifest.yaml # create resource(s)
70+
kubectl apply -f ./my1.yaml -f ./my2.yaml # create from multiple files
71+
kubectl apply -f ./dir # create resource(s) in all manifest files in dir
72+
kubectl apply -f https://git.io/vPieo # create resource(s) from url
73+
kubectl create deployment nginx --image=nginx # start a single instance of nginx
74+
kubectl explain pods # get the documentation for pod manifests
75+
76+
# Create multiple YAML objects from stdin
77+
cat <<EOF | kubectl apply -f -
78+
apiVersion: v1
79+
kind: Pod
80+
metadata:
81+
name: busybox-sleep
82+
spec:
83+
containers:
84+
- name: busybox
85+
image: busybox
86+
args:
87+
- sleep
88+
- "1000000"
89+
---
90+
apiVersion: v1
91+
kind: Pod
92+
metadata:
93+
name: busybox-sleep-less
94+
spec:
95+
containers:
96+
- name: busybox
97+
image: busybox
98+
args:
99+
- sleep
100+
- "1000"
101+
EOF
102+
103+
# Create a secret with several keys
104+
cat <<EOF | kubectl apply -f -
105+
apiVersion: v1
106+
kind: Secret
107+
metadata:
108+
name: mysecret
109+
type: Opaque
110+
data:
111+
password: $(echo -n "s33msi4" | base64 -w0)
112+
username: $(echo -n "jane" | base64 -w0)
113+
EOF
114+
```
115+
116+
### Viewing, Finding Resources
117+
118+
```bash
119+
# Get commands with basic output
120+
kubectl get services # List all services in the namespace
121+
kubectl get pods --all-namespaces # List all pods in all namespaces
122+
kubectl get pods -o wide # List all pods in the current namespace, with more details
123+
kubectl get deployment my-dep # List a particular deployment
124+
kubectl get pods # List all pods in the namespace
125+
kubectl get pod my-pod -o yaml # Get a pod's YAML
126+
127+
# Describe commands with verbose output
128+
kubectl describe nodes my-node
129+
kubectl describe pods my-pod
130+
131+
# List Services Sorted by Name
132+
kubectl get services --sort-by=.metadata.name
133+
134+
# List pods Sorted by Restart Count
135+
kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'
136+
137+
# List PersistentVolumes sorted by capacity
138+
kubectl get pv --sort-by=.spec.capacity.storage
139+
140+
# Get the version label of all pods with label app=cassandra
141+
kubectl get pods --selector=app=cassandra -o \
142+
jsonpath='{.items[*].metadata.labels.version}'
143+
144+
# Get all worker nodes (use a selector to exclude results that have a label
145+
# named 'node-role.kubernetes.io/master')
146+
kubectl get node --selector='!node-role.kubernetes.io/master'
147+
148+
# Get all running pods in the namespace
149+
kubectl get pods --field-selector=status.phase=Running
150+
151+
# Get ExternalIPs of all nodes
152+
kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'
153+
154+
# List Names of Pods that belong to Particular RC
155+
# "jq" command useful for transformations that are too complex for jsonpath, it can be found at https://stedolan.github.io/jq/
156+
sel=${$(kubectl get rc my-rc --output=json | jq -j '.spec.selector | to_entries | .[] | "\(.key)=\(.value),"')%?}
157+
echo $(kubectl get pods --selector=$sel --output=jsonpath={.items..metadata.name})
158+
159+
# Show labels for all pods (or any other Kubernetes object that supports labelling)
160+
kubectl get pods --show-labels
161+
162+
# Check which nodes are ready
163+
JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' \
164+
&& kubectl get nodes -o jsonpath="$JSONPATH" | grep "Ready=True"
165+
166+
# List all Secrets currently in use by a pod
167+
kubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniq
168+
169+
# List all containerIDs of initContainer of all pods
170+
# Helpful when cleaning up stopped containers, while avoiding removal of initContainers.
171+
kubectl get pods --all-namespaces -o jsonpath='{range .items[*].status.initContainerStatuses[*]}{.containerID}{"\n"}{end}' | cut -d/ -f3
172+
173+
# List Events sorted by timestamp
174+
kubectl get events --sort-by=.metadata.creationTimestamp
175+
176+
# Compares the current state of the cluster against the state that the cluster would be in if the manifest was applied.
177+
kubectl diff -f ./my-manifest.yaml
178+
```
179+
180+
### Updating Resources
181+
182+
```bash
183+
kubectl set image deployment/frontend www=image:v2 # Rolling update "www" containers of "frontend" deployment, updating the image
184+
kubectl rollout history deployment/frontend # Check the history of deployments including the revision
185+
kubectl rollout undo deployment/frontend # Rollback to the previous deployment
186+
kubectl rollout undo deployment/frontend --to-revision=2 # Rollback to a specific revision
187+
kubectl rollout status -w deployment/frontend # Watch rolling update status of "frontend" deployment until completion
188+
kubectl rollout restart deployment/frontend # Rolling restart of the "frontend" deployment
189+
190+
191+
cat pod.json | kubectl replace -f - # Replace a pod based on the JSON passed into std
192+
193+
# Force replace, delete and then re-create the resource. Will cause a service outage.
194+
kubectl replace --force -f ./pod.json
195+
196+
# Create a service for a replicated nginx, which serves on port 80 and connects to the containers on port 8000
197+
kubectl expose rc nginx --port=80 --target-port=8000
198+
199+
# Update a single-container pod's image version (tag) to v4
200+
kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f -
201+
202+
kubectl label pods my-pod new-label=awesome # Add a Label
203+
kubectl annotate pods my-pod icon-url=http://goo.gl/XXBTWq # Add an annotation
204+
kubectl autoscale deployment foo --min=2 --max=10 # Auto scale a deployment "foo"
205+
```
206+
207+
### Patching Resources
208+
209+
```bash
210+
# Partially update a node
211+
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'
212+
213+
# Update a container's image; spec.containers[*].name is required because it's a merge key
214+
kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'
215+
216+
# Update a container's image using a json patch with positional arrays
217+
kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]'
218+
219+
# Disable a deployment livenessProbe using a json patch with positional arrays
220+
kubectl patch deployment valid-deployment --type json -p='[{"op": "remove", "path": "/spec/template/spec/containers/0/livenessProbe"}]'
221+
222+
# Add a new element to a positional array
223+
kubectl patch sa default --type='json' -p='[{"op": "add", "path": "/secrets/1", "value": {"name": "whatever" } }]'
224+
```
225+
226+
### Editing Resources
227+
228+
Edit any API resource in your preferred editor.
229+
230+
```bash
231+
kubectl edit svc/docker-registry # Edit the service named docker-registry
232+
KUBE_EDITOR="nano" kubectl edit svc/docker-registry # Use an alternative editor
233+
```
234+
235+
### Scaling Resources
236+
237+
```bash
238+
kubectl scale --replicas=3 rs/foo # Scale a replicaset named 'foo' to 3
239+
kubectl scale --replicas=3 -f foo.yaml # Scale a resource specified in "foo.yaml" to 3
240+
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql # If the deployment named mysql's current size is 2, scale mysql to 3
241+
kubectl scale --replicas=5 rc/foo rc/bar rc/baz # Scale multiple replication controllers
242+
```
243+
244+
### Deleting Resources
245+
246+
```bash
247+
kubectl delete -f ./pod.json # Delete a pod using the type and name specified in pod.json
248+
kubectl delete pod,service baz foo # Delete pods and services with same names "baz" and "foo"
249+
kubectl delete pods,services -l name=myLabel # Delete pods and services with label name=myLabel
250+
kubectl -n my-ns delete pod,svc --all # Delete all pods and services in namespace my-ns,
251+
# Delete all pods matching the awk pattern1 or pattern2
252+
kubectl get pods -n mynamespace --no-headers=true | awk '/pattern1|pattern2/{print $1}' | xargs kubectl delete -n mynamespace pod
253+
```
254+
255+
### Interacting with running Pods
256+
257+
```bash
258+
kubectl logs my-pod # dump pod logs (stdout)
259+
kubectl logs -l name=myLabel # dump pod logs, with label name=myLabel (stdout)
260+
kubectl logs my-pod --previous # dump pod logs (stdout) for a previous instantiation of a container
261+
kubectl logs my-pod -c my-container # dump pod container logs (stdout, multi-container case)
262+
kubectl logs -l name=myLabel -c my-container # dump pod logs, with label name=myLabel (stdout)
263+
kubectl logs my-pod -c my-container --previous # dump pod container logs (stdout, multi-container case) for a previous instantiation of a container
264+
kubectl logs -f my-pod # stream pod logs (stdout)
265+
kubectl logs -f my-pod -c my-container # stream pod container logs (stdout, multi-container case)
266+
kubectl logs -f -l name=myLabel --all-containers # stream all pods logs with label name=myLabel (stdout)
267+
kubectl run -i --tty busybox --image=busybox -- sh # Run pod as interactive shell
268+
kubectl run nginx --image=nginx --restart=Never -n
269+
mynamespace # Run pod nginx in a specific namespace
270+
kubectl run nginx --image=nginx --restart=Never # Run pod nginx and write its spec into a file called pod.yaml
271+
--dry-run -o yaml > pod.yaml
272+
273+
kubectl attach my-pod -i # Attach to Running Container
274+
kubectl port-forward my-pod 5000:6000 # Listen on port 5000 on the local machine and forward to port 6000 on my-pod
275+
kubectl exec my-pod -- ls / # Run command in existing pod (1 container case)
276+
kubectl exec my-pod -c my-container -- ls / # Run command in existing pod (multi-container case)
277+
kubectl top pod POD_NAME --containers # Show metrics for a given pod and its containers
278+
```
279+
280+
### Interacting with Nodes and Cluster
281+
282+
```bash
283+
kubectl cordon my-node # Mark my-node as unschedulable
284+
kubectl drain my-node # Drain my-node in preparation for maintenance
285+
kubectl uncordon my-node # Mark my-node as schedulable
286+
kubectl top node my-node # Show metrics for a given node
287+
kubectl cluster-info # Display addresses of the master and services
288+
kubectl cluster-info dump # Dump current cluster state to stdout
289+
kubectl cluster-info dump --output-directory=/path/to/cluster-state # Dump current cluster state to /path/to/cluster-state
290+
291+
# If a taint with that key and effect already exists, its value is replaced as specified.
292+
kubectl taint nodes foo dedicated=special-user:NoSchedule
293+
```
294+
295+
#### Resource types
296+
297+
List all supported resource types along with their shortnames, [API group](https://kubernetes.io/docs/concepts/overview/kubernetes-api/#api-groups), whether they are [namespaced](https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces), and [Kind](https://kubernetes.io/docs/concepts/overview/working-with-objects/kubernetes-objects):
298+
299+
```bash
300+
kubectl api-resources
301+
```
302+
303+
Other operations for exploring API resources:
304+
305+
```bash
306+
kubectl api-resources --namespaced=true # All namespaced resources
307+
kubectl api-resources --namespaced=false # All non-namespaced resources
308+
kubectl api-resources -o name # All resources with simple output (just the resource name)
309+
kubectl api-resources -o wide # All resources with expanded (aka "wide") output
310+
kubectl api-resources --verbs=list,get # All resources that support the "list" and "get" request verbs
311+
kubectl api-resources --api-group=extensions # All resources in the "extensions" API group
312+
```
313+
314+
#### Formatting output
315+
316+
To output details to your terminal window in a specific format, add the `-o` (or `--output`) flag to a supported `kubectl` command.
317+
318+
| Output format | Description |
319+
| ----------------------------------- | -------------------------------- |
320+
| `-o=custom-columns=<spec>` | Print a table using a comma separated list of custom columns files |
321+
| `-o=custom-columns-file=<filename>` | Print a table using the custom columns template in the <filename> file |
322+
| `-o=json` | Output a JSON formatted API object |
323+
| `-o=jsonpath=<template>` | Print the fields defined in a [jsonpath](https://kubernetes.io/docs/reference/kubectl/jsonpath) expression |
324+
| `-o=jsonpath-file=<filename>` | Print the fields defined by the [jsonpath](https://kubernetes.io/docs/reference/kubectl/jsonpath) expression in the <filename> file |
325+
| `-o=name` | Print only the resource name and nothing else |
326+
| `-o=wide` | Output in the plain-text format with any additional information, and for pods, the node name is included |
327+
| `-o=yaml` | Output a YAML formatted API object |
328+
329+
Examples using `-o=custom-columns`:
330+
331+
```bash
332+
# All images running in a cluster
333+
kubectl get pods -A -o=custom-columns='DATA:spec.containers[*].image'
334+
335+
# All images excluding "k8s.gcr.io/coredns:1.6.2"
336+
kubectl get pods -A -o=custom-columns='DATA:spec.containers[?(@.image!="k8s.gcr.io/coredns:1.6.2")].image'
337+
338+
# All fields under metadata regardless of name
339+
kubectl get pods -A -o=custom-columns='DATA:metadata.*'
340+
```
341+
342+
More examples in the kubectl [reference documentation](https://kubernetes.io/docs/reference/kubectl/overview/#custom-columns).
343+
344+
#### Kubectl output verbosity and debugging
345+
346+
Kubectl verbosity is controlled with the `-v` or `--v` flags followed by an integer representing the log level. General Kubernetes logging conventions and the associated log levels are described [here](https://github.com/kubernetes/community/blob/master/contributors/devel/sig-instrumentation/logging.md).
347+
348+
| Verbosity | Description |
349+
| ----------------------------------- | -------------------------------- |
350+
| `--v=0` | Generally useful for this to always be visible to a cluster operator. |
351+
| `--v=1` | A reasonable default log level if you don’t want verbosity. |
352+
| `--v=2` | Useful steady state information about the service and important log messages that may correlate to significant changes in the system. This is the recommended default log level for most systems. |
353+
| `--v=3` | Extended information about changes. |
354+
| `--v=4` | Debug level verbosity. |
355+
| `--v=6` | Display requested resources. |
356+
| `--v=7` | Display HTTP request headers. |
357+
| `--v=8` | Display HTTP request contents. |
358+
| `--v=9` | Display HTTP request contents without truncation of contents. |
359+
360+
## See Also
361+
362+
* [Official tutorial](https://kubernetes.io/docs/tutorials/)
363+
* Learn more about [Overview of kubectl](https://kubernetes.io/docs/reference/kubectl/overview/)
364+
* See [kubectl](https://kubernetes.io/docs/reference/kubectl/kubectl/) options
365+
* Also [kubectl Usage Conventions](https://kubernetes.io/docs/reference/kubectl/conventions/) to understand how to use it in reusable scripts
366+
* See more community [kubectl cheatsheets](https://github.com/dennyzhang/cheatsheet-kubernetes-A4)

0 commit comments

Comments
 (0)