Tuesday 2 July 2024

Introduction to kubectl

 

kubectl
:
  • command line (CLI) tool for Kubernetes
  • command line utility known as the kube command line tool or kubectl or kube control 
  • used to:
    • interact with the Kubernetes cluster(s)
    • enables the interaction (to run commands against) the clusters in order to manage and inspect them
    • create pods, services and other components
    • deploy and manage applications on a Kubernetes cluster
      • kubectl run command is used to deploy an application on the cluster
      • example: kubectl run hello-minikube
    • inspect and manage cluster resources e.g. get cluster information
      • kubectl cluster-info command is used to view information about the cluster
    • get the status of other nodes in the cluster
      • kubectl get nodes command is used to list all the nodes part of the cluster
    • view logs

Installation on Linux


To check if kubectl is installed:

$ kubectl
Command 'kubectl' not found, but can be installed with:
sudo snap install kubectl


To install kubectl (on Linux), follow instructions from here: Install and Set Up kubectl on Linux | Kubernetes.


kubectl CLI



$ kubectl --help
kubectl controls the Kubernetes cluster manager.

 Find more information at: https://kubernetes.io/docs/reference/kubectl/

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 features on objects

Basic Commands (Intermediate):
  explain         Get documentation for a resource
  get             Display one or many resources
  edit            Edit a resource on the server
  delete          Delete resources by file names, stdin, resources and names, or by resources and label selector

Deploy Commands:
  rollout         Manage the rollout of a resource
  scale           Set a new size for a deployment, replica set, or replication controller
  autoscale       Auto-scale a deployment, replica set, stateful set, or replication controller

Cluster Management Commands:
  certificate     Modify certificate resources
  cluster-info    Display cluster information
  top             Display resource (CPU/memory) usage
  cordon          Mark node as unschedulable
  uncordon        Mark node as schedulable
  drain           Drain node in preparation for maintenance
  taint           Update the taints 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
  debug           Create debugging sessions for troubleshooting workloads and nodes
  events          List events

Advanced Commands:
  diff            Diff the live version against a would-be applied version
  apply           Apply a configuration to a resource by file name or stdin
  patch           Update fields of a resource
  replace         Replace a resource by file name or stdin
  wait            Experimental: Wait for a specific condition on one or many resources
  kustomize       Build a kustomization target from a directory or URL

Settings Commands:
  label           Update the labels on a resource
  annotate        Update the annotations on a resource
  completion      Output shell completion code for the specified shell (bash, zsh, fish, or powershell)

Subcommands provided by plugins:

Other Commands:
  api-resources   Print the supported API resources on the server
  api-versions    Print the supported API versions on the server, in the form of "group/version"
  config          Modify kubeconfig files
  plugin          Provides utilities for interacting with plugins
  version         Print the client and server version information

Usage:
  kubectl [flags] [options]

Use "kubectl <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).


Kubectl Configuration


kubectl needs to be configured so it knows:
  • what the current context is (to which cluster/master node it needs to talk to)
  • on behalf of which user it will authenticate with the cluster and also authentication method

$KUBECONFIG environment variable contains the path to the directory that contains minikube configuration which is usually ~/.kube/.

Upon fresh kubectl installation, before it's configured, ~/.kube/ is not created and KUBECONFIG is not specified.

Default kubectl config file is ~/.kube/config. It initially does not exist and before we use kubectl to talk to Kubernetes cluster we need to create it or it can be created by chosen cluster provisioner tool:
 
  • If we use Minikube, on its startup - when we execute minikube start. Be careful as Minikube might overwrite existing kubeconfig file!
  • To create or update the Kubeconfig file for AWS EKS: 
aws eks update-kubeconfig --name <cluster-name> --region <region>


To learn more about kubeconfig file: What is a kubeconfig file? | Enable Sysadmin

Here is the list of all kubectl commands which deal with configuration:

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

 The loading order follows these rules:

  1.  If the --kubeconfig flag is set, then only that file is loaded. The flag may only be set once and no merging takes
place.
  2.  If $KUBECONFIG environment variable is set, then it is used as a list of paths (normal path delimiting rules for
your system). These paths are merged. When a value is modified, it is modified in the file that defines the stanza. When
a value is created, it is created in the first file that exists. If no files in the chain exist, then it creates the
last file in the list.
  3.  Otherwise, ${HOME}/.kube/config is used and no merging takes place.

Available Commands:
  current-context   Display the current-context
  delete-cluster    Delete the specified cluster from the kubeconfig
  delete-context    Delete the specified context from the kubeconfig
  delete-user       Delete the specified user from the kubeconfig
  get-clusters      Display clusters defined in the kubeconfig
  get-contexts      Describe one or many contexts
  get-users         Display users defined in the kubeconfig
  rename-context    Rename a context from the kubeconfig file
  set               Set an individual value in a kubeconfig file
  set-cluster       Set a cluster entry in kubeconfig
  set-context       Set a context entry in kubeconfig
  set-credentials   Set a user entry in kubeconfig
  unset             Unset an individual value in a kubeconfig file
  use-context       Set the current-context in a kubeconfig file
  view              Display merged kubeconfig settings or a specified kubeconfig file

Usage:
  kubectl config SUBCOMMAND [options]

Use "kubectl config <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).


To check the current kubectl configuration:

$ kubectl config view


Kubectl Contexts



Kubectl utility can work with multiple clusters, local or remote, at the same time.
Kubectl context is basically a cluster and its configuration, that kubectl is currently operating on. 

To list all contexts in the local kubectl config:

$ kubectl config get-contexts
CURRENT   NAME     CLUSTER     AUTHINFO     NAMESPACE
          n1       n1          n1                 
          n2       n2          n2                         
*         minikube minikube    minikube     default   

where

n1 = arn:aws:eks:eu-west-2:47xxxxxxx18:cluster/example-voting-app
n2 = arn:aws:eks:eu-west-2:47xxxxxxx18:cluster/nginx-cluster 


Asterisk (*) above denotes the current context.


To switch contexts:

$ kubectl config set current-context <context_name>


To view the cluster information:

$ kubectl cluster-info


Starting the Minikube automatically switches kubectl context to it:

% minikube start
Done! kubectl is now configured to use "minikube" cluster and "default" namespace by default  

If we then stop Minikube, no context will be selected.


Kubectl Users


Kubeconfig file contains an attribute users which can look like:

users:
- name: arn:aws:eks:us-east-1:17xxxxxxxxx15:cluster/my-cluster-beta
  user:
    exec:
      apiVersion: client.authentication.k8s.io/v1beta1
      args:
      - --region
      - us-east-1
      - eks
      - get-token
      - --cluster-name
      - my-cluster
      - --output
      - json
      command: aws
      env:
      - name: AWS_PROFILE
        value: my-kubectl-profile-beta
      interactiveMode: IfAvailable
      provideClusterInfo: false
- name: minikube
  user:
    client-certificate: /Users/bojan/.minikube/profiles/minikube/client.crt
    client-key: /Users/bojan/.minikube/profiles/minikube/client.key


In this example, each user is authenticated in a different way.

AWS EKS user is authenticated via AWS IAM Authentication for AWS EKS. User obtains temporary token via aws eks get-token by using the profile as set in AWS_PROFILE. This profile must be present in ~/.aws/credentials.


 
Minikube user is authenticated via Certificate-based authentication.


References:


No comments: