Kubernetes kubectl: Difference between revisions

From 탱이의 잡동사니
Jump to navigation Jump to search
No edit summary
 
(31 intermediate revisions by the same user not shown)
Line 1: Line 1:
== Overview ==
== Overview ==
Kubectl 명령어 내용 정리
Kubectl 명령어 내용 정리
== Basic ==
Kubectl 은 kubernetes cluser manager console 로, kubernetes 를 제어할 때 사용되는 cli 툴이다.
== Command categories ==
Kubectl 의 명령과 옵션은 다음과 같은 카테고리로 구분될 수 있다. 자세한 내용은 이곳<ref>https://kubernetes.io/docs/reference/kubectl/overview/</ref>을 참조하면 된다.
=== Basic commands (Beginner) ===
* create : Create a resource from a file or from stdin.
* expose : Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service.
* run : Run a particular image on the cluster.
* set : Set specific feature on objects.
* run-container : Run a particular image on the cluster. This command is deprecated, use "run" instead.
=== Basic commands (Intermediate) ===
* get : Display one or many resources.
* explain : Documentation of resources.
* edit : Edit a resource on the server.
* delete : Delete resources by filename, stdin, resources and names, or by resources and label selector.
=== Deploy  commands ===
* rollout : Manage the rollout of a resource.
* rolling-update : Perform a rolling update of the given RelicationController.
* scale : Set a new size for a Deployment, ReplicaSet, Replication Controller, or Job.
* autoscale : Auto-scale a Deployment, ReplicaSet, or ReplicationController.
=== Cluster management commands ===
* certificate : Modify certiciate resources.
* cluster-info : Display cluster info.
* top : Display Resource (CPU/Memory/Storage) usage.
* cordon : Mark node as unschedulable.
* uncordon : Mark node as schedualbe.
* drain : Drain node in preparation for maintenance.
* taint : Update the traints on one or more nodes.
=== Troubleshooting and Debugging commands ===
* describe : Show details of a specific resource or group of resources.
* logs : Print the logs for a container in a pod.
* attach : Attach to a running container.
* exec : Execute a command in a container.
* port-forward : Forward one or more local ports to a pod.
* proxy : Run a proxy to the Kubernetes API server.
* cp : Copy files and directories to and from containers.
* auth : Inspect authorization.
== Configuration file ==
To access the Kubernetes cluster, the kubectl client needs the master node endpoint and appropriate credentials to be able to interact with the API server running on the master node.
While starting the Minikube, the startup process creates, by default, a configuration file, config, inside the .kube directory(often referred to as the dot-kube-config file), which resides in the user's home directory. The configuration file has all the connection details required by kubectl.
By default, the kubectl binary parses this file to find the master node's connection endpoint, along with credentials. To look at the connection details, we can either see the content of the ~/.kube/config file or run the following command.
<pre>
$ kubectl config view
apiVersion: v1
clusters:
- cluster:
    certificate-authority: /Users/sungtaekim/.minikube/ca.crt
    server: https://192.168.99.101:8443
  name: minikube
contexts:
- context:
    cluster: minikube
    user: minikube
  name: minikube
current-context: minikube
kind: Config
preferences: {}
users:
- name: minikube
  user:
    client-certificate: /Users/sungtaekim/.minikube/client.crt
    client-key: /Users/sungtaekim/.minikube/client.key
</pre>


== Actions ==
== Actions ==
=== exec ===
Execute a command in a container.
=== logs ===
Print the logs for a container in a pod or specified resource. If the pod has only one container, the container name is optional.
==== Examples ====
<pre>
</pre>
=== proxy ===
Creates a proxy server or application-level gateway between localhost and the Kubernetes API server. It also allows serving static content over the specified HTTP path. All incoming data enters through one port and gets forwarded to the remote Kubernetes API server port, except for the path matching the static content path.
=== run ===
=== run ===
The run command creates a new deployment. This performed a few things.
The run command creates a new deployment. This performed a few things.
Line 9: Line 95:
* Configured the cluster to reschedule the instance on a new Node when needed.
* Configured the cluster to reschedule the instance on a new Node when needed.


=== get ===
=== scale ===
Set a new allows users to specify one or more preconditions for the scale action.
 
Scale also allows users to specify one or more preconditions for the scale action.
 
If --current-replicas or --resource-version is specified, it is validated before
 
== config ==
Modify kubeconfig files using subcommands like "kubectl config set current-context my-context".
 
=== kubectl config use-context <context name> ===
Sets the current-context in a kubeconfig file.
 
<pre>
$ kubectl config use-context minikube
Switched to context "minikube".
</pre>
 
=== kubectl config view ===
Display merged kubeconfig setting or a specified kubeconfig file.
 
<pre>
$ kubectl config view
apiVersion: v1
clusters:
- cluster:
    certificate-authority: /Users/sungtaekim/.minikube/ca.crt
    server: https://192.168.99.101:8443
  name: minikube
contexts:
- context:
    cluster: minikube
    user: minikube
  name: minikube
current-context: minikube
kind: Config
preferences: {}
users:
- name: minikube
  user:
    client-certificate: /Users/sungtaekim/.minikube/client.crt
    client-key: /Users/sungtaekim/.minikube/client.key
</pre>
 
== cluster-info ==
Display cluster info.
<pre>
$ kubectl cluster-info
Kubernetes master is running at https://192.168.99.101:8443
KubeDNS is running at https://192.168.99.101:8443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
</pre>
 
== describe ==
Show details of a specific resource or group of resources.
 
Print a detailed description of the selected resources, including related resources such as events or controllers. You may select a single object by name, all objects of that type, provide a name prefix, or label selector. For example:
 
<pre>
$ kubectl describe TYPE NAME_PREFIX
</pre>
will first check for an exact match on TYPE and NAME PREFIX. If no such resource exists, it will output details for every resource that has a name prefixed with NAME PREFIX.
 
Use "kubectl api-resources" for a complete list of supported resources.
<pre>
Describe a node.
kubectl describe nodes kubernetes-node-emt8.c.myproject.internal
 
</pre>
 
=== nodes ===
 
=== pods ===
 
=== deployment ===
==== Example ====
<pre>
$ kubectl describe deployments kubernetes-bootcamp
Name:                  kubernetes-bootcamp
Namespace:              default
CreationTimestamp:      Thu, 02 May 2019 11:23:50 +0000
Labels:                run=kubernetes-bootcamp
Annotations:            deployment.kubernetes.io/revision: 1
Selector:              run=kubernetes-bootcamp
Replicas:              4 desired | 4 updated | 4 total | 4 available | 0 unavailable
StrategyType:          RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  run=kubernetes-bootcamp
  Containers:
  kubernetes-bootcamp:
    Image:        gcr.io/google-samples/kubernetes-bootcamp:v1
    Port:        8080/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:      <none>
  Volumes:        <none>
Conditions:
  Type          Status  Reason
  ----          ------  ------
  Progressing    True    NewReplicaSetAvailable
  Available      True    MinimumReplicasAvailable
OldReplicaSets:  <none>
NewReplicaSet:  kubernetes-bootcamp-6bf84cb898 (4/4 replicas created)
Events:
  Type    Reason            Age  From                  Message
  ----    ------            ----  ----                  -------
  Normal  ScalingReplicaSet  22m  deployment-controller  Scaled up replica set kubernetes-bootcamp-6bf84cb898 to 1
  Normal  ScalingReplicaSet  10m  deployment-controller  Scaled up replica set kubernetes-bootcamp-6bf84cb898 to 4
$ kubectl describe deployments/kubernetes-bootcamp
Name:                  kubernetes-bootcamp
Namespace:              default
CreationTimestamp:      Thu, 02 May 2019 11:23:50 +0000
Labels:                run=kubernetes-bootcamp
Annotations:            deployment.kubernetes.io/revision: 1
Selector:              run=kubernetes-bootcamp
Replicas:              4 desired | 4 updated | 4 total | 4 available | 0 unavailable
StrategyType:          RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  run=kubernetes-bootcamp
  Containers:
  kubernetes-bootcamp:
    Image:        gcr.io/google-samples/kubernetes-bootcamp:v1
    Port:        8080/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:      <none>
  Volumes:        <none>
Conditions:
  Type          Status  Reason
  ----          ------  ------
  Progressing    True    NewReplicaSetAvailable
  Available      True    MinimumReplicasAvailable
OldReplicaSets:  <none>
NewReplicaSet:  kubernetes-bootcamp-6bf84cb898 (4/4 replicas created)
Events:
  Type    Reason            Age  From                  Message
  ----    ------            ----  ----                  -------
  Normal  ScalingReplicaSet  22m  deployment-controller  Scaled up replica set kubernetes-bootcamp-6bf84cb898 to 1
  Normal  ScalingReplicaSet  10m  deployment-controller  Scaled up replica set kubernetes-bootcamp-6bf84cb898 to 4
</pre>
 
== get ==
Display one or many resources.
Display one or many resources.


Line 17: Line 247:


By specifying the output as 'template' and providing a Go template as the value of the --template flag, you can filter the attributes of the fetched resources.
By specifying the output as 'template' and providing a Go template as the value of the --template flag, you can filter the attributes of the fetched resources.
=== pods ===
List all pods in ps output format.
==== Example ====
<pre>
$ kubectl get pods -o wide
NAME                                  READY  STATUS    RESTARTS  AGE    IP          NODE      NOMINATED NODE  READINESS GATES
kubernetes-bootcamp-6bf84cb898-7n6g4  1/1    Running  0          13m    172.18.0.4  minikube  <none>        <none>
kubernetes-bootcamp-6bf84cb898-87l4t  1/1    Running  0          116s  172.18.0.6  minikube  <none>        <none>
kubernetes-bootcamp-6bf84cb898-t4mht  1/1    Running  0          116s  172.18.0.5  minikube  <none>        <none>
kubernetes-bootcamp-6bf84cb898-wf6f9  1/1    Running  0          116s  172.18.0.7  minikube  <none>        <none>
</pre>
== proxy ==
Creates a proxy server or application-level gateway between localhost and the Kubernetes API Server. It also allows serving static content over the specified HTTP path.
All incoming data enters through one port and gets forwarded to the remote kubernetes API Server port, except for the path matching the static content path.
=== kubctl proxy ===
<pre>
$ kubectl proxy
Starting to serve on 127.0.0.1:8001
</pre>
== rollout ==
Manage the rollout of a resource.
Valid resource types.
* deployments
* daemonsets
* statefulsets
== set ==
Configure application resources.
<pre>
$ kubectl set SUBCOMMAND [options]
</pre>
=== env ===
Update environment variables on a pod template.
=== image ===
Update image of a pod template.
==== Example ====
<pre>
$ kubectl set image deployment/kubernetes-bootcamp kubernetes-bootcamp=jocatalin/kubernetes-bootcamp:v2
deployment.apps/kubernetes-bootcamp image updated
</pre>
=== resources ===
Update resource requests/limits on objects with pod templates.
=== selector ===
Set the selector on a resource.
=== subject ===
Update User, Group or ServiceAccount in a RoleBinding/ClusterRoleBinding.


== ETC ==
== ETC ==
=== Version ===
<pre>
<pre>
$ kubectl version
$ kubectl version
Line 25: Line 317:
</pre>
</pre>


[[category:system]]
=== Access kubernetes without proxy ===
When not using the kubctl proxy, we need to authenticate to the API server when sedning API requests. We can authenticate by providing a Bearer Token when issuing a curl, or by providing a set of keys and certificates.
 
A Bearer Token is an access token which is generated by the authentication server (the API server on the master node) and given back to the client. Using that token the client can connect back to the kubernetes API server without providing further authentication details, and then, access resources.
* Get the token
<pre>
$ TOKEN=$(kubectl describe secret -n kube-system $(kubectl get secrets -n kube-system | grep default | cut -f1 -d ' ') | grep -E '^token' | cut -f2 -d':' | tr -d '\t' | tr -d " ")
</pre>
 
* Get the API server endpoint
<pre>
$ APISERVER=$(kubectl config view | grep https | cut -f 2- -d ":" | tr -d " ")
</pre>
 
* Confrim that the APISERVER stored the same IP as the kubernetes master IP by issuing the following 2 commands and comparing their outputs.
<pre>
$ echo $APISERVER
https://192.168.99.101:8443
 
$ kubectl cluster-info
Kubernetes master is running at https://192.168.99.101:8443 ...
</pre>
 
* Access the API server using the curl commands, as shown below.
<pre>
$ curl $APISERVER --header "Authorization: Bearer $TOKEN" --insecure
{
"paths": [
  "/api",
  "/api/v1",
  "/apis",
  "/apis/apps",
  ......
  ......
  "/logs",
  "/metrics",
  "/openapi/v2",
  "/version"
]
}
</pre>
 
Instead of the access token, we can extract the client certificate, client key, and certificate authority data from the .kube/config file. Once extracted, they are encoded and then passed with curl command for authentication.
<pre>
$ curl $APISERVER --cert encoded-cert --key encoded-key --cacert encoded-ca
</pre>
 
== References ==
<references />
 
[[category:kubernetes]]

Latest revision as of 23:18, 6 January 2020

Overview

Kubectl 명령어 내용 정리

Basic

Kubectl 은 kubernetes cluser manager console 로, kubernetes 를 제어할 때 사용되는 cli 툴이다.

Command categories

Kubectl 의 명령과 옵션은 다음과 같은 카테고리로 구분될 수 있다. 자세한 내용은 이곳<ref>https://kubernetes.io/docs/reference/kubectl/overview/</ref>을 참조하면 된다.

Basic commands (Beginner)

  • create : Create a resource from a file or from stdin.
  • expose : Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service.
  • run : Run a particular image on the cluster.
  • set : Set specific feature on objects.
  • run-container : Run a particular image on the cluster. This command is deprecated, use "run" instead.

Basic commands (Intermediate)

  • get : Display one or many resources.
  • explain : Documentation of resources.
  • edit : Edit a resource on the server.
  • delete : Delete resources by filename, stdin, resources and names, or by resources and label selector.

Deploy commands

  • rollout : Manage the rollout of a resource.
  • rolling-update : Perform a rolling update of the given RelicationController.
  • scale : Set a new size for a Deployment, ReplicaSet, Replication Controller, or Job.
  • autoscale : Auto-scale a Deployment, ReplicaSet, or ReplicationController.

Cluster management commands

  • certificate : Modify certiciate resources.
  • cluster-info : Display cluster info.
  • top : Display Resource (CPU/Memory/Storage) usage.
  • cordon : Mark node as unschedulable.
  • uncordon : Mark node as schedualbe.
  • drain : Drain node in preparation for maintenance.
  • taint : Update the traints on one or more nodes.

Troubleshooting and Debugging commands

  • describe : Show details of a specific resource or group of resources.
  • logs : Print the logs for a container in a pod.
  • attach : Attach to a running container.
  • exec : Execute a command in a container.
  • port-forward : Forward one or more local ports to a pod.
  • proxy : Run a proxy to the Kubernetes API server.
  • cp : Copy files and directories to and from containers.
  • auth : Inspect authorization.

Configuration file

To access the Kubernetes cluster, the kubectl client needs the master node endpoint and appropriate credentials to be able to interact with the API server running on the master node.

While starting the Minikube, the startup process creates, by default, a configuration file, config, inside the .kube directory(often referred to as the dot-kube-config file), which resides in the user's home directory. The configuration file has all the connection details required by kubectl.

By default, the kubectl binary parses this file to find the master node's connection endpoint, along with credentials. To look at the connection details, we can either see the content of the ~/.kube/config file or run the following command.

$ kubectl config view
apiVersion: v1
clusters:
- cluster:
    certificate-authority: /Users/sungtaekim/.minikube/ca.crt
    server: https://192.168.99.101:8443
  name: minikube
contexts:
- context:
    cluster: minikube
    user: minikube
  name: minikube
current-context: minikube
kind: Config
preferences: {}
users:
- name: minikube
  user:
    client-certificate: /Users/sungtaekim/.minikube/client.crt
    client-key: /Users/sungtaekim/.minikube/client.key

Actions

exec

Execute a command in a container.

logs

Print the logs for a container in a pod or specified resource. If the pod has only one container, the container name is optional.

Examples


proxy

Creates a proxy server or application-level gateway between localhost and the Kubernetes API server. It also allows serving static content over the specified HTTP path. All incoming data enters through one port and gets forwarded to the remote Kubernetes API server port, except for the path matching the static content path.

run

The run command creates a new deployment. This performed a few things.

  • Searched for a suitable node where an instance of the application could be run.
  • Scheduled the application to run on that Node.
  • Configured the cluster to reschedule the instance on a new Node when needed.

scale

Set a new allows users to specify one or more preconditions for the scale action.

Scale also allows users to specify one or more preconditions for the scale action.

If --current-replicas or --resource-version is specified, it is validated before

config

Modify kubeconfig files using subcommands like "kubectl config set current-context my-context".

kubectl config use-context <context name>

Sets the current-context in a kubeconfig file.

$ kubectl config use-context minikube
Switched to context "minikube".

kubectl config view

Display merged kubeconfig setting or a specified kubeconfig file.

$ kubectl config view
apiVersion: v1
clusters:
- cluster:
    certificate-authority: /Users/sungtaekim/.minikube/ca.crt
    server: https://192.168.99.101:8443
  name: minikube
contexts:
- context:
    cluster: minikube
    user: minikube
  name: minikube
current-context: minikube
kind: Config
preferences: {}
users:
- name: minikube
  user:
    client-certificate: /Users/sungtaekim/.minikube/client.crt
    client-key: /Users/sungtaekim/.minikube/client.key

cluster-info

Display cluster info.

$ kubectl cluster-info
Kubernetes master is running at https://192.168.99.101:8443
KubeDNS is running at https://192.168.99.101:8443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

describe

Show details of a specific resource or group of resources.

Print a detailed description of the selected resources, including related resources such as events or controllers. You may select a single object by name, all objects of that type, provide a name prefix, or label selector. For example:

$ kubectl describe TYPE NAME_PREFIX

will first check for an exact match on TYPE and NAME PREFIX. If no such resource exists, it will output details for every resource that has a name prefixed with NAME PREFIX.

Use "kubectl api-resources" for a complete list of supported resources.

Describe a node.
kubectl describe nodes kubernetes-node-emt8.c.myproject.internal

nodes

pods

deployment

Example

$ kubectl describe deployments kubernetes-bootcamp
Name:                   kubernetes-bootcamp
Namespace:              default
CreationTimestamp:      Thu, 02 May 2019 11:23:50 +0000
Labels:                 run=kubernetes-bootcamp
Annotations:            deployment.kubernetes.io/revision: 1
Selector:               run=kubernetes-bootcamp
Replicas:               4 desired | 4 updated | 4 total | 4 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  run=kubernetes-bootcamp
  Containers:
   kubernetes-bootcamp:
    Image:        gcr.io/google-samples/kubernetes-bootcamp:v1
    Port:         8080/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Progressing    True    NewReplicaSetAvailable
  Available      True    MinimumReplicasAvailable
OldReplicaSets:  <none>
NewReplicaSet:   kubernetes-bootcamp-6bf84cb898 (4/4 replicas created)
Events:
  Type    Reason             Age   From                   Message
  ----    ------             ----  ----                   -------
  Normal  ScalingReplicaSet  22m   deployment-controller  Scaled up replica set kubernetes-bootcamp-6bf84cb898 to 1
  Normal  ScalingReplicaSet  10m   deployment-controller  Scaled up replica set kubernetes-bootcamp-6bf84cb898 to 4
$ kubectl describe deployments/kubernetes-bootcamp
Name:                   kubernetes-bootcamp
Namespace:              default
CreationTimestamp:      Thu, 02 May 2019 11:23:50 +0000
Labels:                 run=kubernetes-bootcamp
Annotations:            deployment.kubernetes.io/revision: 1
Selector:               run=kubernetes-bootcamp
Replicas:               4 desired | 4 updated | 4 total | 4 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  run=kubernetes-bootcamp
  Containers:
   kubernetes-bootcamp:
    Image:        gcr.io/google-samples/kubernetes-bootcamp:v1
    Port:         8080/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Progressing    True    NewReplicaSetAvailable
  Available      True    MinimumReplicasAvailable
OldReplicaSets:  <none>
NewReplicaSet:   kubernetes-bootcamp-6bf84cb898 (4/4 replicas created)
Events:
  Type    Reason             Age   From                   Message
  ----    ------             ----  ----                   -------
  Normal  ScalingReplicaSet  22m   deployment-controller  Scaled up replica set kubernetes-bootcamp-6bf84cb898 to 1
  Normal  ScalingReplicaSet  10m   deployment-controller  Scaled up replica set kubernetes-bootcamp-6bf84cb898 to 4

get

Display one or many resources.

Prints a table of the most important information about the specified resources. You can filter the list using a label selector and the --selector flag. If the desired resource type is namespaced you will only see results in your current namespace unless you pass --all-namespaces.

Uninitialized objects are not shown unless --include-uninitialized is passed.

By specifying the output as 'template' and providing a Go template as the value of the --template flag, you can filter the attributes of the fetched resources.

pods

List all pods in ps output format.

Example

$ kubectl get pods -o wide
NAME                                   READY   STATUS    RESTARTS   AGE    IP           NODE       NOMINATED NODE   READINESS GATES
kubernetes-bootcamp-6bf84cb898-7n6g4   1/1     Running   0          13m    172.18.0.4   minikube   <none>        <none>
kubernetes-bootcamp-6bf84cb898-87l4t   1/1     Running   0          116s   172.18.0.6   minikube   <none>        <none>
kubernetes-bootcamp-6bf84cb898-t4mht   1/1     Running   0          116s   172.18.0.5   minikube   <none>        <none>
kubernetes-bootcamp-6bf84cb898-wf6f9   1/1     Running   0          116s   172.18.0.7   minikube   <none>        <none>

proxy

Creates a proxy server or application-level gateway between localhost and the Kubernetes API Server. It also allows serving static content over the specified HTTP path.

All incoming data enters through one port and gets forwarded to the remote kubernetes API Server port, except for the path matching the static content path.

kubctl proxy

$ kubectl proxy
Starting to serve on 127.0.0.1:8001

rollout

Manage the rollout of a resource.

Valid resource types.

  • deployments
  • daemonsets
  • statefulsets

set

Configure application resources.

$ kubectl set SUBCOMMAND [options]

env

Update environment variables on a pod template.

image

Update image of a pod template.

Example

$ kubectl set image deployment/kubernetes-bootcamp kubernetes-bootcamp=jocatalin/kubernetes-bootcamp:v2
deployment.apps/kubernetes-bootcamp image updated

resources

Update resource requests/limits on objects with pod templates.

selector

Set the selector on a resource.

subject

Update User, Group or ServiceAccount in a RoleBinding/ClusterRoleBinding.

ETC

Version

$ kubectl version
Client Version: version.Info{Major:"1", Minor:"13", GitVersion:"v1.13.3", GitCommit:"721bfa751924da8d1680787490c54b9179b1fed0", GitTreeState:"clean", BuildDate:"2019-02-01T20:08:12Z", GoVersion:"go1.11.5", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"13", GitVersion:"v1.13.3", GitCommit:"721bfa751924da8d1680787490c54b9179b1fed0", GitTreeState:"clean", BuildDate:"2019-02-01T20:00:57Z", GoVersion:"go1.11.5", Compiler:"gc", Platform:"linux/amd64"}

Access kubernetes without proxy

When not using the kubctl proxy, we need to authenticate to the API server when sedning API requests. We can authenticate by providing a Bearer Token when issuing a curl, or by providing a set of keys and certificates.

A Bearer Token is an access token which is generated by the authentication server (the API server on the master node) and given back to the client. Using that token the client can connect back to the kubernetes API server without providing further authentication details, and then, access resources.

  • Get the token
$ TOKEN=$(kubectl describe secret -n kube-system $(kubectl get secrets -n kube-system | grep default | cut -f1 -d ' ') | grep -E '^token' | cut -f2 -d':' | tr -d '\t' | tr -d " ")
  • Get the API server endpoint
$ APISERVER=$(kubectl config view | grep https | cut -f 2- -d ":" | tr -d " ")
  • Confrim that the APISERVER stored the same IP as the kubernetes master IP by issuing the following 2 commands and comparing their outputs.
$ echo $APISERVER
https://192.168.99.101:8443

$ kubectl cluster-info
Kubernetes master is running at https://192.168.99.101:8443 ...
  • Access the API server using the curl commands, as shown below.
$ curl $APISERVER --header "Authorization: Bearer $TOKEN" --insecure
{
 "paths": [
   "/api",
   "/api/v1",
   "/apis",
   "/apis/apps",
   ......
   ......
   "/logs",
   "/metrics",
   "/openapi/v2",
   "/version"
 ]
}

Instead of the access token, we can extract the client certificate, client key, and certificate authority data from the .kube/config file. Once extracted, they are encoded and then passed with curl command for authentication.

$ curl $APISERVER --cert encoded-cert --key encoded-key --cacert encoded-ca

References

<references />