Kubectl: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(31 intermediate revisions by the same user not shown)
Line 1: Line 1:
=External=
* kubectl commands: https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands
=Internal=
=Internal=


Line 4: Line 6:
* [[Kubernetes Concepts#Overview|Kubernetes Concepts]]
* [[Kubernetes Concepts#Overview|Kubernetes Concepts]]
* [[Amazon_EKS_Operations#Connect_to_an_EKS_Cluster_with_kubectl|Connect to an EKS Cluster with kubectl]]
* [[Amazon_EKS_Operations#Connect_to_an_EKS_Cluster_with_kubectl|Connect to an EKS Cluster with kubectl]]
* [[oc]]


=Overview=
=Overview=


<tt>kubectl</tt> is the main Kubernetes command line tool, used to send REST API requests with JSON-formatted payloads into the [[Kubernetes_Control_Plane_and_Data_Plane_Concepts#API_Server|API server]].
<tt>kubectl</tt> is the main Kubernetes command line tool, used to send REST API requests with JSON-formatted payloads into the [[Kubernetes_Control_Plane_and_Data_Plane_Concepts#API_Server|API server]].
=Concepts=
==Context==
{{Internal|.kube_config#Contexts|.kube_config Context}}


=Installation=
=Installation=
Line 48: Line 55:


=Commands=
=Commands=
====<tt>port-forward</tt>====
{{Internal|kubectl port-foward|port-forward}}
====<tt>expose</tt>====
{{Internal|kubectl expose|expose}}
====<tt>version</tt>====
{{Internal|kubectl version|version}}
====<tt>config</tt>====
{{Internal|kubectl config|config}}
====<tt>apply</tt>, <tt>create</tt>, <tt>edit</tt>, <tt>patch</tt>, <tt>kustomize</tt>, <tt>delete</tt>====
* [[kubectl apply|apply]]
* [[kubectl create|create]]
* [[kubectl edit|edit]]
* [[kubectl patch|patch]]
* [[kubectl kustomize|kustomize]]
* [[kubectl delete|delete]]


* [[kubectl port-foward|port-forward]]
====<tt>wait</tt>====
* [[kubectl expose|expose]]
{{Internal|kubectl wait|wait}}
* [[kubectl version|version]]
====<tt>cp</tt>====
* [[kubectl config|config]]
{{Internal|kubectl cp|cp}}
* [[kubectl apply|apply]], [[kubectl create|create]], [[kubectl edit|edit]], [[kubectl patch|patch]], [[kubectl kustomize|kustomize]]
====<tt>exec</tt>====
* [[kubectl wait|wait]]
{{Internal|kubectl exec|exec}}
* [[kubectl cp|cp]]
====<tt>auth</tt>====
* [[kubectl exec|exec]]
{{Internal|kubectl auth|auth}}
* [[kubectl auth|auth]]
====<tt>run</tt>====
* [[kubectl delete|delete]]
{{Internal|kubectl run|run}}
* [[kubectl run|run]]
====<tt>scale</tt>====
{{Internal|kubectl scale|scale}}
====<tt>logs</tt>====
{{Internal|kubectl logs|logs}}


=Options=
=Options=
Line 69: Line 94:
</syntaxhighlight>
</syntaxhighlight>


where the log level is an integer between 0 and 10.
where the log level is an integer between 0 and 10.
 
Also see [[#Low-Level_Network_Logging|Low-Level Network Logging]] below.


==--as==
==--as==
Line 80: Line 107:


This is particularly useful when experimenting with permission and authorization, by using [[Kubectl auth|kubectl auth can-i]].
This is particularly useful when experimenting with permission and authorization, by using [[Kubectl auth|kubectl auth can-i]].
==--token==
{{Internal|Kubernetes_Security_Concepts#Bearer_Tokens|Bearer Tokens in Kubernetes}}
==--user==
Specifies which user credentials from [[.kube_config|.kube/config]] to use with the current command.
==--raw==
Access APIs.
<syntaxhighlight lang='bash'>
kubectl get --raw /apis/metrics.k8s.io | jq
</syntaxhighlight>


=Obtaining Information about the API Server=
=Obtaining Information about the API Server=
Line 98: Line 141:
==get==
==get==


kubectl get
{{External|https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#get}}


<tt>kubectl get</tt> and <tt>kubectl describe</tt> mask sensitive information such as a [[Kubernetes Cluster Configuration Concepts#Secret|secret]]'s content to protect it from being exposed accidentally to an onlooker or from being stored in a terminal log.
<syntaxhighlight lang='bash'>
kubectl get
</syntaxhighlight>
 
<code>kubectl get</code> and <tt>kubectl describe</tt> mask sensitive information such as a [[Kubernetes Cluster Configuration Concepts#Secret|secret]]'s content to protect it from being exposed accidentally to an onlooker or from being stored in a terminal log.


===Output in YAML Format===
===Output in YAML Format===
Line 106: Line 153:
The "-o yaml" option instructs get to return the full copy of the object's manifest from the cluster store. The output is divided into a <tt>.spec</tt> section, which represents the desired state and the <tt>.status</tt> section, which represents the [[Kubernetes Concepts#Current_State|current observed state]].
The "-o yaml" option instructs get to return the full copy of the object's manifest from the cluster store. The output is divided into a <tt>.spec</tt> section, which represents the desired state and the <tt>.status</tt> section, which represents the [[Kubernetes Concepts#Current_State|current observed state]].


kubectl get -o yaml ...
<syntaxhighlight lang='bash'>
kubectl get -o yaml ...
</syntaxhighlight>


===Get the Manifest for an Existing Object===
===Get the Manifest for an Existing Object===


The manifest can be used to recreate the object:
The manifest can be used to recreate the object:
kubectl get pod ''pod-name'' --export -o yaml
Note that --export is deprecated and will be removed in the future so find an equivalent.
===Custom Columns===
Custom columns are specified by <HEADER>:<JSONPATH-EXPRESSION>,...


<syntaxhighlight lang='bash'>
<syntaxhighlight lang='bash'>
kubectl get ... -o custom-columns='KIND:kind,NAMESPACE:metadata.namespace,NAME:metadata.name,SERVICE_ACCOUNTS:subjects[?(@.kind=="ServiceAccount")].name'
kubectl get pod ''pod-name'' --export -o yaml
</syntaxhighlight>
</syntaxhighlight>


===JSONPath Support===
Note that --export is deprecated and will be removed in the future so find an equivalent.


{{External|https://kubernetes.io/docs/reference/kubectl/jsonpath/}}
===<span id='Get_with_Selector'></span>Get with Selector (-l,--selector)===
{{External|https://goessner.net/articles/JsonPath/}}


====Removing Leading and Trailing Single Quotes====
Use -l|--selector to specify a selector (label query) to filter on. The expression supports '=', '==', and '!='.


<syntaxhighlight lang='text'>
<syntaxhighlight lang='text'>
... | sed -e 's/^'\''//' > ...
kubectl get pod -l color=green,shape=square
</syntaxhighlight>
kubectl get pod --selector=color=green,shape=square
 
====Get an Individual Attribute Only====
 
<font color=darkgray>TODO: https://gist.github.com/so0k/42313dbb3b547a0f51a547bb968696ba</font>
 
kubectl ... -o jsonpath="{.status.phase}"
 
kubectl ... -o jsonpath="{.items[?(@.spec.unschedulable)].metadata.name}"
 
<font color=darkgray>
Alternative, to explore and document:
 
kubectl get pods  --no-headers -o custom-columns=\":metadata.name\" ...
 
</font>
 
====Filter Elements of an Array based on a Key Value====
 
We assume that the elements of the array are maps, which contain the specified key:
 
kubectl ... -o jsonpath="{.users[?(@.name=="blue")].user.password}"
kubectl get pod ... -o jsonpath='{.items[0].spec.volumes[?(@.name=="vault")].hostPath.path}' 2>/dev/null
 
====Select and Combine Two or More Elements====
<syntaxhighlight lang='bash'>
kubectl get pod \
-o jsonpath='{.items[0].spec.volumes[?(@.name=="A")].hostPath.path}'+'{.items[0].spec.volumes[?(@.name=="B")].hostPath.path}'
</syntaxhighlight>
</syntaxhighlight>


returns "/some/path/a+/some/path/b"
===Common Columns===
 
====Same Element from Multiple Resources====
<syntaxhighlight lang='bash'>
<syntaxhighlight lang='bash'>
kubectl get pod -o jsonpath='{.items[*].metadata.name}'
kubectl get ... -o NAME ...
</syntaxhighlight>
</syntaxhighlight>


====TODO====
===Custom Columns===
<syntaxhighlight lang='bash'>
kubectl get pods -o=jsonpath='{.items[?(@.metadata.labels.name=="web")].metadata.name}'
</syntaxhighlight>


=====Iterate over the Elements of an Array=====
Custom columns are specified by <HEADER>:<JSONPATH-EXPRESSION>,...
<syntaxhighlight lang='bash'>
kubectl get nodes -o jsonpath='{.items[*]}'
</syntaxhighlight>


=====Iterate over the Elements of an Array and Select a Specific Key=====
<syntaxhighlight lang='bash'>
<syntaxhighlight lang='bash'>
kubectl get nodes -o jsonpath='{.items[*].status}'
kubectl get ... -o custom-columns='KIND:kind,NAMESPACE:metadata.namespace,NAME:metadata.name,SERVICE_ACCOUNTS:subjects[?(@.kind=="ServiceAccount")].name'
</syntaxhighlight>
</syntaxhighlight>


Filter by an element:
===JSONPath Support===
{{Internal|kubectl get JSONPath Support|kubectl get JSONPath Support}}
===<tt>--field-selector</tt>===
{{Internal|kubectl get field-selector Support|kubectl get field-selector Support}}
===<tt>--all-namespaces</tt>===
<syntaxhighlight lang='bash'>
<syntaxhighlight lang='bash'>
kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="InternalIP")]}'
kubectl get --all-namespaces pods
</syntaxhighlight>
</syntaxhighlight>
 
===Additional Details===
Print the element "address"
<syntaxhighlight lang='bash'>
<syntaxhighlight lang='bash'>
kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="InternalIP")].address}'
kubectl get -o wide [...]
</syntaxhighlight>
</syntaxhighlight>


Line 204: Line 211:
  kubectl apply -f ''filename''.yaml
  kubectl apply -f ''filename''.yaml


=Port Fowarding=
=Port Forwarding=
 
<syntaxhighlight lang='bash'>
  while ! kubectl -n my-namespace port-forward service/my-service 8787:8787; do sleep 1; done
while ! kubectl -n my-namespace port-forward service/my-service 8787:8787; do sleep 1; done
</syntaxhighlight>
=Low-Level Network Logging=
The system environment variable DEBUG enables low-level network logging (even if it is set to false, as in <code>DEBUG=false</code>):
<syntaxhighlight lang='text'>
I0518 04:13:58.436899  23832 log.go:181] (0xc0000fc000) (0xc000c92000) Create stream
</syntaxhighlight>
To disable it:
<syntaxhighlight lang='bash'>
unset DEBUG
</syntaxhighlight>

Latest revision as of 23:18, 5 August 2024

External

Internal

Overview

kubectl is the main Kubernetes command line tool, used to send REST API requests with JSON-formatted payloads into the API server.

Concepts

Context

.kube_config Context

Installation

https://kubernetes.io/docs/tasks/tools/install-kubectl/

Linux

Download the latest version:

curl -LO https://storage.googleapis.com/kubernetes-release/release/`curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt`/bin/linux/amd64/kubectl

Make the binary executable:

chmod +x ./kubectl

Move the binary into the PATH

sudo mv ./kubectl /usr/local/bin/kubectl

Mac

Download the latest version:

curl -LO "https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/darwin/amd64/kubectl"

Then place into /usr/local/bin and make it executable.

Configuration

.kube config

Rescue Access

On a master, as root:

/usr/local/bin/kubectl  --kubeconfig=/etc/kubernetes/admin.conf get pods

Commands

port-forward

port-forward

expose

expose

version

version

config

config

apply, create, edit, patch, kustomize, delete

wait

wait

cp

cp

exec

exec

auth

auth

run

run

scale

scale

logs

logs

Options

-v

kubectl -v=<log-level> ...

where the log level is an integer between 0 and 10.

Also see Low-Level Network Logging below.

--as

--as allows to pass a username to impersonate for the operation. In this context, a "username" can also be the name of a service account in the format "system:serviceaccount:<namespace-name>:<service-account-name>":

kubectl --as system:serviceaccount:blue:blue-sa apply -f ./pod.yaml

This is particularly useful when experimenting with permission and authorization, by using kubectl auth can-i.

--token

Bearer Tokens in Kubernetes

--user

Specifies which user credentials from .kube/config to use with the current command.

--raw

Access APIs.

kubectl get --raw /apis/metrics.k8s.io | jq

Obtaining Information about the API Server

API Server URL

kubectl config view -o json | jq -r '.clusters[] | select(.name | contains("docker")) | .cluster.server'

API Server Bearer Token

kubectl get secrets -o jsonpath="{.items[?(@.metadata.annotations['kubernetes\.io/service-account\.name']=='default')].data.token}"|base64 --decode

Obtaining Information about API Objects

get

https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#get
kubectl get

kubectl get and kubectl describe mask sensitive information such as a secret's content to protect it from being exposed accidentally to an onlooker or from being stored in a terminal log.

Output in YAML Format

The "-o yaml" option instructs get to return the full copy of the object's manifest from the cluster store. The output is divided into a .spec section, which represents the desired state and the .status section, which represents the current observed state.

kubectl get -o yaml ...

Get the Manifest for an Existing Object

The manifest can be used to recreate the object:

kubectl get pod ''pod-name'' --export -o yaml

Note that --export is deprecated and will be removed in the future so find an equivalent.

Get with Selector (-l,--selector)

Use -l|--selector to specify a selector (label query) to filter on. The expression supports '=', '==', and '!='.

kubectl get pod -l color=green,shape=square
kubectl get pod --selector=color=green,shape=square

Common Columns

kubectl get ... -o NAME ...

Custom Columns

Custom columns are specified by <HEADER>:<JSONPATH-EXPRESSION>,...

kubectl get ... -o custom-columns='KIND:kind,NAMESPACE:metadata.namespace,NAME:metadata.name,SERVICE_ACCOUNTS:subjects[?(@.kind=="ServiceAccount")].name'

JSONPath Support

kubectl get JSONPath Support

--field-selector

kubectl get field-selector Support

--all-namespaces

kubectl get --all-namespaces pods

Additional Details

kubectl get -o wide [...]

describe

The 'describe' command provides a multi-line overview of an object. It includes important object lifecycle events.

kubectl describe

POSTing a Manifest

kubectl apply -f filename.yaml

Port Forwarding

while ! kubectl -n my-namespace port-forward service/my-service 8787:8787; do sleep 1; done

Low-Level Network Logging

The system environment variable DEBUG enables low-level network logging (even if it is set to false, as in DEBUG=false):

I0518 04:13:58.436899   23832 log.go:181] (0xc0000fc000) (0xc000c92000) Create stream

To disable it:

unset DEBUG