Container Orchestration/Kubernetes

Kubernetes 플러그인 매니저 Krew란?

Somaz 2023. 4. 30. 13:28
728x90
반응형

Overview

오늘은 Kubernetes 플러그인을 관리하는 패키지 매니저인 Krew에 대해 공부해보려고 한다.

 


Krew란?

KrewKubernetes 클러스터와 상호 작용하기 위한 명령줄 도구인 kubectl의 플러그인 관리자이다.

Krew를 사용하면 kubectl의 기능을 확장하는 추가 플러그인을 쉽게 검색, 설치 및 관리한다. 플러그인은 패키지로 배포되며 Kubernetes 커뮤니티에서 관리하는 플러그인의 중앙 저장소인 Krew 인덱스에서 호스팅할 수 있다.


Krew 설치

 

krew 설치

 

아래의 명령어를 사용하면 설치가 된다.

(
  set -x; cd "$(mktemp -d)" &&
  OS="$(uname | tr '[:upper:]' '[:lower:]')" &&
  ARCH="$(uname -m | sed -e 's/x86_64/amd64/' -e 's/\(arm\)\(64\)\?.*/\1\2/' -e 's/aarch64$/arm64/')" &&
  KREW="krew-${OS}_${ARCH}" &&
  curl -fsSLO "https://github.com/kubernetes-sigs/krew/releases/latest/download/${KREW}.tar.gz" &&
  tar zxvf "${KREW}.tar.gz" &&
  ./"${KREW}" install krew
)
++ mktemp -d
+ cd /tmp/tmp.RkH52djNKx
++ uname
++ tr '[:upper:]' '[:lower:]'
+ OS=linux
++ uname -m
++ sed -e s/x86_64/amd64/ -e 's/\(arm\)\(64\)\?.*/\1\2/' -e 's/aarch64$/arm64/'
+ ARCH=amd64
+ KREW=krew-linux_amd64
+ curl -fsSLO https://github.com/kubernetes-sigs/krew/releases/latest/download/krew-linux_amd64.tar.gz
+ tar zxvf krew-linux_amd64.tar.gz
./LICENSE
./krew-linux_amd64
+ ./krew-linux_amd64 install krew
Adding "default" plugin index from https://github.com/kubernetes-sigs/krew-index.git.
Updated the local copy of plugin index.
Installing plugin: krew
Installed plugin: krew
\
 | Use this plugin:
 |      kubectl krew
 | Documentation:
 |      https://krew.sigs.k8s.io/
 | Caveats:
 | \
 |  | krew is now installed! To start using kubectl plugins, you need to add
 |  | krew's installation directory to your PATH:
 |  |
 |  |   * macOS/Linux:
 |  |     - Add the following to your ~/.bashrc or ~/.zshrc:
 |  |         export PATH="${KREW_ROOT:-$HOME/.krew}/bin:$PATH"
 |  |     - Restart your shell.
 |  |
 |  |   * Windows: Add %USERPROFILE%\.krew\bin to your PATH environment variable
 |  |
 |  | To list krew commands and to get help, run:
 |  |   $ kubectl krew
 |  | For a full list of available plugins, run:
 |  |   $ kubectl krew search
 |  |
 |  | You can find documentation at
 |  |   https://krew.sigs.k8s.io/docs/user-guide/quickstart/.
 | /
/

 

 

krew 환경변수 등록

$ vi ~/.bashrc
# kubectl krew
export PATH="${KREW_ROOT:-$HOME/.krew}/bin:$PATH"

 


kubectx & kubedns 란?

kubectx(context 관리), kubedns(namespace 관리)

kubectxkubens는 컨텍스트와 네임스페이스 간 전환 프로세스를 단순화하여 Kubernetes로 보다 효율적으로 작업하는 데 도움이 되는 두 개의 명령줄 유틸리티이다.

 

$ kubectl krew install ctx
Updated the local copy of plugin index.
Installing plugin: ctx
Installed plugin: ctx
...
WARNING: You installed plugin "ctx" from the krew-index plugin repository.
   These plugins are not audited for security by the Krew maintainers.
   Run them at your own risk.
   
$ kubectl krew install ns
Updated the local copy of plugin index.
Installing plugin: ns
Installed plugin: ns
...
WARNING: You installed plugin "ns" from the krew-index plugin repository.
   These plugins are not audited for security by the Krew maintainers.
   Run them at your own risk.


$ git clone https://github.com/ahmetb/kubectx ./kubectx
Cloning into './kubectx'...
remote: Enumerating objects: 1482, done.
remote: Counting objects: 100% (197/197), done.
remote: Compressing objects: 100% (112/112), done.
remote: Total 1482 (delta 98), reused 162 (delta 78), pack-reused 1285
Receiving objects: 100% (1482/1482), 911.95 KiB | 4.49 MiB/s, done.
Resolving deltas: 100% (830/830), done.

$ cd kubectx/

~/kubectx$ ls
CONTRIBUTING.md  LICENSE  README.md  cmd  completion  go.mod  go.sum  img  internal  kubectx  kubens  test

~/kubectx$ sudo cp kubectx /usr/local/bin/
~/kubectx$ sudo cp kubens /usr/local/bin/

$ kubectl krew list
PLUGIN  VERSION
ctx     v0.9.4
krew    v0.4.3
ns      v0.9.4

 


 

kubectx

kubectx를 사용하면 서로 다른 Kubernetes 컨텍스트 간에 쉽게 전환할 수 있다.

컨텍스트는 Kubernetes 구성 파일(일반적으로 ~/.kube/config)에 정의되며 작업 중인 클러스터, 사용자 및 네임스페이스에 대한 정보를 저장한다.

kubectx를 사용하면 구성 파일을 수동으로 편집하지 않고도 다른 클러스터 또는 사용자 구성 간에 빠르게 전환할 수 있다. 

  • kubectx: 사용 가능한 컨텍스트를 나열한다.
  • kubectx <context_name>: 지정된 컨텍스트로 전환한다.
  • kubectx -d <context_name>: 지정된 컨텍스트를 삭제한다.

 

kubectx 사용법

$ kubectx
arn:aws:eks:ap-northeast-1:123456789012:cluster/EKS1
arn:aws:eks:ap-northeast-1:123456789013:cluster/EKS2
arn:aws:eks:ap-northeast-2:123456789012:cluster/EKS3
arn:aws:eks:ap-northeast-2:123456789013:cluster/EKS4

$ kubectl config get-contexts
CURRENT   NAME                                                        CLUSTER                                                     AUTHINFO                                                   NAMESPACE
          arn:aws:eks:ap-northeast-1:123456789012:cluster/EKS1        arn:aws:eks:ap-northeast-1:123456789012:cluster/EKS1        arn:aws:eks:ap-northeast-1:123456789012:cluster/EKS1

          arn:aws:eks:ap-northeast-1:123456789013:cluster/EKS2        arn:aws:eks:ap-northeast-1:123456789013:cluster/EKS2        arn:aws:eks:ap-northeast-1:123456789013:cluster/EKS2

          arn:aws:eks:ap-northeast-2:123456789012:cluster/EKS3        arn:aws:eks:ap-northeast-2:123456789012:cluster/EKS3        arn:aws:eks:ap-northeast-1:123456789012:cluster/EKS3

*         arn:aws:eks:ap-northeast-2:123456789013:cluster/EKS4        arn:aws:eks:ap-northeast-2:123456789013:cluster/EKS4        arn:aws:eks:ap-northeast-1:123456789013:cluster/EKS4

$ kubectx arn:aws:eks:ap-northeast-2:123456789012:cluster/EKS3

$ kubectl config get-contexts
CURRENT   NAME                                                        CLUSTER                                                     AUTHINFO                                                   NAMESPACE
          arn:aws:eks:ap-northeast-1:123456789012:cluster/EKS1        arn:aws:eks:ap-northeast-1:123456789012:cluster/EKS1        arn:aws:eks:ap-northeast-1:123456789012:cluster/EKS1

          arn:aws:eks:ap-northeast-1:123456789013:cluster/EKS2        arn:aws:eks:ap-northeast-1:123456789013:cluster/EKS2        arn:aws:eks:ap-northeast-1:123456789013:cluster/EKS2

*         arn:aws:eks:ap-northeast-2:123456789012:cluster/EKS3        arn:aws:eks:ap-northeast-2:123456789012:cluster/EKS3        arn:aws:eks:ap-northeast-1:123456789012:cluster/EKS3

          arn:aws:eks:ap-northeast-2:123456789013:cluster/EKS4        arn:aws:eks:ap-northeast-2:123456789013:cluster/EKS4        arn:aws:eks:ap-northeast-1:123456789013:cluster/EKS4

 


 

kubens

kubens는 현재 컨텍스트 내에서 Kubernetes 네임스페이스 간에 전환하는 데 도움이 된다.

네임스페이스는 Kubernetes 클러스터 내에서 리소스를 구성하는 방법으로 리소스 격리 및 관리를 개선할 수 있다.

kubens를 사용하면 구성 파일을 수동으로 편집하지 않고도 활성 네임스페이스를 빠르게 변경할 수 있다.

  • kubens: 사용 가능한 네임스페이스를 나열합니다.
  • kubens <namespace>: 지정된 네임스페이스로 전환

 

kubens 사용법

$ kubens
default
dev1
dev2
kube-node-lease
kube-public
kube-system

$ kubens kube-system

$ k get po
NAME                                                              READY   STATUS    RESTARTS   AGE
aws-load-balancer-controller-865cd8df88-djt9m                     1/1     Running   0          123d
aws-load-balancer-controller-865cd8df88-tlf4z                     1/1     Running   0          123d
coredns-c96679f98-9bt9k                                           1/1     Running   0          123d
coredns-c96679f98-vk559                                           1/1     Running   0          123d
dev1-kubernetes-external-secrets-8545gpwd5                        1/1     Running   0          104d
dev2-kubernetes-external-secrets-59f6gv5c8                        1/1     Running   0          10d

$ kubens dev1

$ k get po
NAME                    READY   STATUS    RESTARTS   AGE
dev1-76fc65969d-4bcxm   1/1     Running   0          23m

kube-ps1란?

kube-ps1는 multi cluster에서 사용자의 실수를 줄여주는 bash와 zsh을 위한 kubernetes prompt이다.

그리고 현재 Context와 Namespace를 표시해주는 명령어이다.

bash를 기준으로 작성하였습니다.

 

kube-ps1 설치

$ git clone https://github.com/jonmosco/kube-ps1.git

 

~/.bashrc 추가

$ vi ~/.bashrc

source ~/eks/kube-ps1/kube-ps1.sh
PS1='[\u@\h \W $(kube_ps1)]\$ '
KUBE_PS1_SYMBOL_ENABLE=false
KUBE_PS1_SYMBOL_COLOR=null
KUBE_PS1_CTX_COLOR=red
KUBE_PS1_NS_COLOR=null

function get_cluster_short() {
  echo "$1" | cut -d / -f2
}

KUBE_PS1_CLUSTER_FUNCTION=get_cluster_short

 

kube-ps1 사용법

$ bashrc 적용
somaz@AD01769994:~$ source ~/.bashrc

[somaz@AD01769994 ~ (EKS4)]$ kubectx
arn:aws:eks:ap-northeast-1:123456789012:cluster/EKS1
arn:aws:eks:ap-northeast-1:123456789013:cluster/EKS2
arn:aws:eks:ap-northeast-2:123456789012:cluster/EKS3
arn:aws:eks:ap-northeast-2:123456789013:cluster/EKS4

[somaz@AD01769994 ~ (EKS4)]$ kubectx arn:aws:eks:ap-northeast-2:123456789012:cluster/EKS3

# on/off
[somaz@AD01769994 ~ (EKS3)]$ kubeoff

[somaz@AD01769994 ~ ]$ kubeon

[somaz@AD01769994 ~ (EKS3)]$

kubectl-neat 란?

kubectl 명령어 결과에서 불필요한 정보를 정리하여 가독성있게 읽을 수 있게 해준다.

 

neat 설치

$ kubectl krew install neat
Updated the local copy of plugin index.
Installing plugin: neat
Installed plugin: neat
\
 | Use this plugin:
 |      kubectl neat
 | Documentation:
 |      https://github.com/itaysk/kubectl-neat
/
WARNING: You installed plugin "neat" from the krew-index plugin repository.
   These plugins are not audited for security by the Krew maintainers.
   Run them at your own risk.

 

neat 사용법

$ k get deployments.apps coredns -o yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "2"
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{},"labels":{"eks.amazonaws.com/component":"coredns","k8s-app":"kube-dns","kubernetes.io/name":"CoreDNS"},"name":"coredns","namespace":"kube-system"},"spec":{"replicas":2,"selector":{"matchLabels":{"eks.amazonaws.com/component":"coredns","k8s-app":"kube-dns"}},"strategy":{"rollingUpdate":{"maxUnavailable":1},"type":"RollingUpdate"},"template":{"metadata":{"annotations":{"eks.amazonaws.com/compute-type":"ec2"},"labels":{"eks.amazonaws.com/component":"coredns","k8s-app":"kube-dns"}},"spec":{"affinity":{"nodeAffinity":{"requiredDuringSchedulingIgnoredDuringExecution":{"nodeSelectorTerms":[{"matchExpressions":[{"key":"beta.kubernetes.io/os","operator":"In","values":["linux"]},{"key":"beta.kubernetes.io/arch","operator":"In","values":["amd64","arm64"]}]}]}},"podAntiAffinity":{"preferredDuringSchedulingIgnoredDuringExecution":[{"podAffinityTerm":{"labelSelector":{"matchExpressions":[{"key":"k8s-app","operator":"In","values":["kube-dns"]}]},"topologyKey":"kubernetes.io/hostname"},"weight":100}]}},"containers":[{"args":["-conf","/etc/coredns/Corefile"],"image":"602401143452.dkr.ecr.ap-northeast-2.amazonaws.com/eks/coredns:v1.8.7-eksbuild.1","imagePullPolicy":"IfNotPresent","livenessProbe":{"failureThreshold":5,"httpGet":{"path":"/health","port":8080,"scheme":"HTTP"},"initialDelaySeconds":60,"successThreshold":1,"timeoutSeconds":5},"name":"coredns","ports":[{"containerPort":53,"name":"dns","protocol":"UDP"},{"containerPort":53,"name":"dns-tcp","protocol":"TCP"},{"containerPort":9153,"name":"metrics","protocol":"TCP"}],"readinessProbe":{"httpGet":{"path":"/health","port":8080,"scheme":"HTTP"}},"resources":{"limits":{"memory":"170Mi"},"requests":{"cpu":"100m","memory":"70Mi"}},"securityContext":{"allowPrivilegeEscalation":false,"capabilities":{"add":["NET_BIND_SERVICE"],"drop":["all"]},"readOnlyRootFilesystem":true},"volumeMounts":[{"mountPath":"/etc/coredns","name":"config-volume","readOnly":true},{"mountPath":"/tmp","name":"tmp"}]}],"dnsPolicy":"Default","priorityClassName":"system-cluster-critical","serviceAccountName":"coredns","tolerations":[{"effect":"NoSchedule","key":"node-role.kubernetes.io/master"},{"key":"CriticalAddonsOnly","operator":"Exists"}],"volumes":[{"emptyDir":{},"name":"tmp"},{"configMap":{"items":[{"key":"Corefile","path":"Corefile"}],"name":"coredns"},"name":"config-volume"}]}}}}
  creationTimestamp: "2022-06-10T06:52:25Z"
  generation: 2
  labels:
    eks.amazonaws.com/component: coredns
    k8s-app: kube-dns
    kubernetes.io/name: CoreDNS
  name: coredns
  namespace: kube-system
  resourceVersion: "180739914"
  uid: f04a76b0-0013-4264-ae7a-47e8bf69c095
spec:
  progressDeadlineSeconds: 600
  replicas: 2
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      eks.amazonaws.com/component: coredns
      k8s-app: kube-dns
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 1
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        eks.amazonaws.com/component: coredns
        k8s-app: kube-dns
 ...

 

아래와 같이 바꿔준다.

$ k get deployments.apps coredns -o yaml |k neat
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "2"
  labels:
    eks.amazonaws.com/component: coredns
    k8s-app: kube-dns
    kubernetes.io/name: CoreDNS
  name: coredns
  namespace: kube-system
spec:
  progressDeadlineSeconds: 600
  replicas: 2
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      eks.amazonaws.com/component: coredns
      k8s-app: kube-dns
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 1
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        eks.amazonaws.com/component: coredns
        k8s-app: kube-dns

kubectl node-shell

쿠버네티스 노드에 원격으로 접속할 수 있다.

  • Context(.kube/config 파일 필수)

node-shell URL

 

node-shell 설치 및 사용

$ kubectl krew index add kvaps https://github.com/kvaps/krew-index
$ kubectl krew install kvaps/node-shell

 

$ k get nodes
NAME      STATUS   ROLES                  AGE    VERSION
master0   Ready    control-plane,master   365d   v1.23.5
node1     Ready    <none>                 365d   v1.23.5
node2     Ready    <none>                 365d   v1.23.5
node3     Ready    <none>                 365d   v1.23.5
node4     Ready    <none>                 365d   v1.23.5
node5     Ready    <none>                 365d   v1.23.5

$ k node-shell master0
spawning "nsenter-xc12na" on "master0"
If you don't see a command prompt, try pressing enter.
root@master0:/# ls

Reference

 

Krew git URL

 

Krew 공식 사이트

 

kube-ps1 git URL

 

neat git URL

 

node-shell git URL

728x90
반응형