[Kubernetes]kubectlのプラグインをインストールする

#はじめに
kubectlはプラグインをインストールすることで、サブコマンドを拡張することができます。今回はこのプラグインのインストール方法を確認したいと思います。

[Extend kubectl with plugins](https://kubernetes.io/docs/tasks/extend-kubectl/kubectl-plugins/)

#krewのインストール
まずはプラグインマネージャのkrewをインストールする必要があります。以下の手順に沿ってMasterノードにインストールします。

https://krew.sigs.k8s.io/docs/user-guide/setup/install/

```
$ (
>   set -x; cd "$(mktemp -d)" &&
>   curl -fsSLO "https://github.com/kubernetes-sigs/krew/releases/latest/download/krew.{tar.gz,yaml}" &&
>   tar zxvf krew.tar.gz &&
>   KREW=./krew-"$(uname | tr '[:upper:]' '[:lower:]')_amd64" &&
>   "$KREW" install --manifest=krew.yaml --archive=krew.tar.gz &&
>   "$KREW" update
> )
++ mktemp -d
+ cd /tmp/tmp.qeCZkgswIN
+ curl -fsSLO 'https://github.com/kubernetes-sigs/krew/releases/latest/download/krew.{tar.gz,yaml}'
+ tar zxvf krew.tar.gz
./LICENSE
./krew-darwin_amd64
./krew-linux_amd64
./krew-linux_arm
./krew-windows_amd64.exe
++ uname
++ tr '[:upper:]' '[:lower:]'
+ KREW=./krew-linux_amd64
+ ./krew-linux_amd64 install --manifest=krew.yaml --archive=krew.tar.gz
Installing plugin: krew
Installed plugin: krew
\
 | Use this plugin:
 |      kubectl krew
 | Documentation:
 |      https://sigs.k8s.io/krew
 | 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://sigs.k8s.io/krew.
 | /
/
+ ./krew-linux_amd64 update
WARNING: To be able to run kubectl plugins, you need to add
the following to your ~/.bash_profile or ~/.bashrc:

    export PATH="${PATH}:${HOME}/.krew/bin"

and restart your shell.

Updated the local copy of plugin index.
```

##PATH環境変数の設定
krewをインストールした時の最後のメッセージに従って、PATHを通しておきます。

```
$ echo "export PATH="${PATH}:${HOME}/.krew/bin"" >> .bashrc
$ . .bashrc
```

##インストールの確認
krew自身もプラグインですので、以下のコマンドでインストールされているプラグインを確認できます。

```
$ kubectl plugin list
The following compatible plugins are available:

/home/kosuke/.krew/bin/kubectl-krew
```

#プラグインの検索
`kubectl krew search`コマンドでインストール可能なプラグインの一覧が表示されます。[こちら](https://github.com/kubernetes-sigs/krew-index/blob/master/plugins.md)でもプラグインの一覧を確認できます。

```
$ kubectl krew search
NAME                            DESCRIPTION                                         INSTALLED
access-matrix                   Show an RBAC access matrix for server resources     no
advise-psp                      Suggests PodSecurityPolicies for cluster.           no
apparmor-manager                Manage AppArmor profiles for cluster.               no
auth-proxy                      Authentication proxy to a pod or service            no
bulk-action                     Do bulk actions on Kubernetes resources.            no
ca-cert                         Print the PEM CA certificate of the current clu...  no
capture                         Triggers a Sysdig capture to troubleshoot the r...  no
cert-manager                    Manage cert-manager resources inside your cluster   no
change-ns                       View or change the current namespace via kubectl.   no
cilium                          Easily interact with Cilium agents.                 no
cluster-group                   Exec commands across a group of contexts.           no
config-cleanup                  Automatically clean up your kubeconfig              no
cssh                            SSH into Kubernetes nodes                           no
ctx                             Switch between contexts in your kubeconfig          no
custom-cols                     A "kubectl get" replacement with customizable c...  no
datadog                         Manage the Datadog Operator                         no
debug                           Attach ephemeral debug container to running pod     no
debug-shell                     Create pod with interactive kube-shell.             no
deprecations                    Checks for deprecated objects in a cluster          no
df-pv                           Show disk usage (like unix df) for persistent v...  no
doctor                          Scans your cluster and reports anomalies.           no
duck                            List custom resources with ducktype support         no
eksporter                       Export resources and removes a pre-defined set ...  no
emit-event                      Emit Kubernetes Events for the requested object     no
evict-pod                       Evicts the given pod                                no
example                         Prints out example manifest YAMLs                   no
exec-as                         Like kubectl exec, but offers a `user` flag to ...  no
exec-cronjob                    Run a CronJob immediately as Job                    no
fields                          Grep resources hierarchy by field name              no
fleet                           Shows config and resources of a fleet of clusters   no
fuzzy                           Fuzzy and partial string search for kubectl         no
gadget                          Gadgets for debugging and introspecting apps        no
get-all                         Like `kubectl get all` but _really_ everything      no
gke-credentials                 Fetch credentials for GKE clusters                  no
gopass                          Imports secrets from gopass                         no
grep                            Filter Kubernetes resources by matching their n...  no
gs                              Handle custom resources with Giant Swarm            no
iexec                           Interactive selection tool for `kubectl exec`       no
images                          Show container images used in the cluster.          no
ingress-nginx                   Interact with ingress-nginx                         no
ipick                           A kubectl wrapper for interactive resource sele...  no
konfig                          Merge, split or import kubeconfig files             no
krew                            Package manager for kubectl plugins.                yes
kubesec-scan                    Scan Kubernetes resources with kubesec.io.          no
kudo                            Declaratively build, install, and run operators...  no
kuttl                           Declaratively run and test operators                no
kyverno                         Kyverno is a policy engine for kubernetes           no
match-name                      Match names of pods and other API objects           no
modify-secret                   modify secret with implicit base64 translations     no
mtail                           Tail logs from multiple pods matching label sel...  no
neat                            Remove clutter from Kubernetes manifests to mak...  no
net-forward                     Proxy to arbitrary TCP services on a cluster ne...  no
node-admin                      List nodes and run privileged pod with chroot       no
node-restart                    Restart cluster nodes sequentially and gracefully   no
node-shell                      Spawn a root shell on a node via kubectl            no
np-viewer                       Network Policies rules viewer                       no
ns                              Switch between Kubernetes namespaces                no
oidc-login                      Log in to the OpenID Connect provider               no
open-svc                        Open the Kubernetes URL(s) for the specified se...  no
operator                        Manage operators with Operator Lifecycle Manager    no
oulogin                         Login to a cluster via OpenUnison                   no
outdated                        Finds outdated container images running in a cl...  no
passman                         Store kubeconfig credentials in keychains or pa...  no
pod-dive                        Shows a pod's workload tree and info inside a node  no
pod-logs                        Display a list of pods to get logs from             no
pod-shell                       Display a list of pods to execute a shell in        no
podevents                       Show events for pods                                no
popeye                          Scans your clusters for potential resource issues   no
preflight                       Executes application preflight tests in a cluster   no
profefe                         Gather and manage pprof profiles from running pods  no
prompt                          Prompts for user confirmation when executing co...  no
prune-unused                    Prune unused resources                              no
psp-util                        Manage Pod Security Policy(PSP) and the related...  no
rbac-lookup                     Reverse lookup for RBAC                             no
rbac-view                       A tool to visualize your RBAC permissions.          no
resource-capacity               Provides an overview of resource requests, limi...  no
resource-snapshot               Prints a snapshot of nodes, pods and HPAs resou...  no
restart                         Restarts a pod with the given name                  no
rm-standalone-pods              Remove all pods without owner references            no
rolesum                         Summarize RBAC roles for subjects                   no
roll                            Rolling restart of all persistent pods in a nam...  no
schemahero                      Declarative database schema migrations via YAML     no
score                           Kubernetes static code analysis.                    no
service-tree                    Status for ingresses, services, and their backends  no
sick-pods                       Find and debug Pods that are "Not Ready"            no
snap                            Delete half of the pods in a namespace or cluster   no
sniff                           Start a remote packet capture on pods using tcp...  no
sort-manifests                  Sort manifest files in a proper order by Kind       no
split-yaml                      Split YAML output into one file per resource.       no
spy                             pod debugging tool for kubernetes clusters with...  no
sql                             Query the cluster via pseudo-SQL                    no
ssh-jump                        A kubectl plugin to SSH into Kubernetes nodes u...  no
sshd                            Run SSH server in a Pod                             no
ssm-secret                      Import/export secrets from/to AWS SSM param store   no
starboard                       Toolkit for finding risks in kubernetes resources   no
status                          Show status details of a given resource.            no
sudo                            Run Kubernetes commands impersonated as group s...  no
support-bundle                  Creates support bundles for off-cluster analysis    no
tail                            Stream logs from multiple pods and containers u...  no
tap                             Interactively proxy Kubernetes Services with ease   no
tmux-exec                       An exec multiplexer using Tmux                      no
topology                        Explore region topology for nodes or pods           no
trace                           bpftrace programs in a cluster                      no
tree                            Show a tree of object hierarchies through owner...  no
unused-volumes                  List unused PVCs                                    no
view-allocations                List allocations per resources, nodes, pods.        no
view-secret                     Decode Kubernetes secrets                           no
view-serviceaccount-kubeconfig  Show a kubeconfig setting to access the apiserv...  no
view-utilization                Shows cluster cpu and memory utilization            no
virt                            Control KubeVirt virtual machines using virtctl     no
warp                            Sync and execute local files in Pod                 no
who-can                         Shows who has RBAC permissions to access Kubern...  no
whoami                          Show the subject that's currently authenticated...  no
```

##プラグインの詳細確認
`kubectl krew info`コマンドで各プラグインの詳細を確認できます。

```
$ kubectl krew info tree
NAME: tree
URI: https://github.com/ahmetb/kubectl-tree/releases/download/v0.4.0/kubectl-tree_v0.4.0_linux_amd64.tar.gz
SHA256: 3253a981099abceb41f2ea32c89489fd1ba459d950becef2e302f79a8b2f0507
VERSION: v0.4.0
HOMEPAGE: https://github.com/ahmetb/kubectl-tree
DESCRIPTION:
This plugin shows sub-resources of a specified Kubernetes API object in a
tree view in the command-line. The parent-child relationship is discovered
using ownerReferences on the child object.

CAVEATS:
\
 | * For resources that are not in default namespace, currently you must
 |   specify -n/--namespace explicitly (the current namespace setting is not
 |   yet used).
/
```

#プラグインのインストール
`kubectl krew install`コマンドを使って、プラグインをインストールします。ここでは「tree」をインストールしてみます。

```
$ kubectl krew install tree
Updated the local copy of plugin index.
Installing plugin: tree
Installed plugin: tree
\
 | Use this plugin:
 |      kubectl tree
 | Documentation:
 |      https://github.com/ahmetb/kubectl-tree
 | Caveats:
 | \
 |  | * For resources that are not in default namespace, currently you must
 |  |   specify -n/--namespace explicitly (the current namespace setting is not
 |  |   yet used).
 | /
/
WARNING: You installed plugin "tree" from the krew-index plugin repository.
   These plugins are not audited for security by the Krew maintainers.
   Run them at your own risk.
```

インストールされていることを確認します。

```
$ kubectl plugin list
The following compatible plugins are available:

/home/kosuke/.krew/bin/kubectl-krew
/home/kosuke/.krew/bin/kubectl-tree
```

#treeの動作確認
インストールしたプラグインの「tree」の動作を確認したいと思います。

```
$ kubectl tree deployment nginx-dep
NAMESPACE  NAME                                 READY  REASON  AGE
default    Deployment/nginx-dep                 -              21d
default    └─ReplicaSet/nginx-dep-7d7d744c9   -              21d
default      └─Pod/nginx-dep-7d7d744c9-gk78k  True           21d
default      └─Pod/nginx-dep-7d7d744c9-mzb9g  True           21d
```
「Deployment - ReplicaSet - Pod」の関連がツリー構造で表示されていますね。

#まとめ
プラグインを利用することで、kubectlコマンドを拡張できることを確認しました。今回はtreeのみを確認しましたが、そのほかにも面白そうなプラグインがたくさんありますね。今度試してみたいと思います。