Azure Kubernetes Services を Azure CLI から色々操作してみる

前回の記事では、AKS を使用する上での環境構築をしました。今回はそのうえで、Azure CLI から AKS を色々いじってみようと思います。

#Azure CLI からのコマンド操作
kubectl を使います。基本的には以下の様な構文を書きます。

```terminal
kubectl [コマンド] [タイプ] [名前] [フラグ]
```

コマンドでは、PowerShell や Command と同じように、`create` `apply` `get` `delete` がよく使用されるみたいです。また、ここでいうタイプは短縮形が可能だそうです。

```terminal
$kubectl get pod
$kubectl get po (短縮名)
$kubectl get deployment
$kubectl get deploy (短縮名)
$kubectl get horizontalprodautoscalers
$kubectl get hpa (短縮名)
```

#よく使うコマンド一覧
ここではよく使うコマンドを記録として残しておこうともいます。その前に、実際Azure CLI で操作をする場合には変数の定義が再度必要になります。以下フォーマットで最初に実行しておくことで、あとあと便利です。たとえば今回は前回記事で作成した AKS に一発で使用できる状態にするコマンドを記載します。

```terminal
$ACR_NAME=komiyasavalacr
$ACR_RES_GROUP=$ACR_NAME
$ACR_ID=$(az acr show --name $ACR_NAME --query id --output tsv)
$SP_NAME=sample-acr-service-principal
$SP_PASSWD=$(az ad sp create-for-rbac --name $SP_NAME --role Reader --scopes $ACR_ID --query password --output tsv)
$APP_ID=$(az ad sp show --id http://$SP_NAME --query appId --output tsv)
$AKS_CLUSTER_NAME=AKSCuster
$AKS_RES_GROUP=$AKS_CLUSTER_NAME
```

##クラスターの情報を表示する
`$kubectl cluster-info`
このコマンドではクラスターの情報が確認することができます。動いている API や アドオン機能の状態が確認できます。

```
miyasaka@Azure:~/Understanding-K8s/chap02$ kubectl cluster-info
Kubernetes master is running at https://akscuster-akscuster-XXXXXXXXXXXXXXXXXXX:443
CoreDNS is running at https://akscuster-akscuster-XXXXXXXXXXXXXXXXXXXXXXXXX:443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
kubernetes-dashboard is running at https://akscuster-akscuster-XXXXXXXXXXXXXXXXXXXXXX:443/api/v1/namespaces/kube-system/services/kubernetes-dashboard/proxy
Metrics-server is running at https://akscuster-akscuster-XXXXXXXXXXXXXXXXXXXXX:443/api/v1/namespaces/kube-system/services/https:metrics-server:/proxy

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
```

##クラスター上の Node の確認
`$kubectl get node`
このコードでは、クラスター上で実行されている Node 一覧を取得することが出来ます。

```
miyasaka@Azure:~/Understanding-K8s/chap02$ kubectl get node
NAME                               STATUS   ROLES   AGE     VERSION
aks-nodepool1-XXXXXXXXXXXXXXXXXX   Ready    agent   3h17m   v1.13.12
aks-nodepool1-XXXXXXXXXXXXXXXXXX   Ready    agent   3h17m   v1.13.12
aks-nodepool1-XXXXXXXXXXXXXXXXXX   Ready    agent   3h17m   v1.13.12
```

`$kubectl get node -o=wide`
上記のコードにオプションとして Wide を付けた形になります。

```
miyasaka@Azure:~/Understanding-K8s/chap02$ kubectl get node -o=wide
NAME                                STATUS   ROLES   AGE     VERSION    INTERNAL-IP   EXTERNAL-IP   OS-IMAGE             KERNEL-VERSION      CONTAINER-RUNTIME
aks-nodepool1-XXXXXXXX-vmss000000   Ready    agent   3h19m   v1.13.12   XX.XXX.X.X    <none>        Ubuntu 16.04.6 LTS   4.15.0-1060-azure   docker://3.0.7
aks-nodepool1-XXXXXXXX-vmss000001   Ready    agent   3h19m   v1.13.12   XX.XXX.X.X    <none>        Ubuntu 16.04.6 LTS   4.15.0-1060-azure   docker://3.0.7
aks-nodepool1-XXXXXXXX-vmss000002   Ready    agent   3h19m   v1.13.12   XX.XXX.X.X    <none>        Ubuntu 16.04.6 LTS   4.15.0-1060-azure   docker://3.0.7
```

##Node の詳細情報表示
`$kubectl describe node aks-nodepool1-XXXXXXXX-vmss000000`
指定した Node の詳細情報を表示します。

```
miyasaka@Azure:~/Understanding-K8s/chap02$ kubectl describe node aks-nodepool1-XXXXXXXX-vmss000000
Name:               aks-nodepool1-XXXXXXXX-vmss000000
Roles:              agent
Labels:             agentpool=nodepool1
                    beta.kubernetes.io/arch=amd64
                    beta.kubernetes.io/instance-type=Standard_DS1_v2
                    beta.kubernetes.io/os=linux
                    failure-domain.beta.kubernetes.io/region=japaneast
                    failure-domain.beta.kubernetes.io/zone=0
                    kubernetes.azure.com/cluster=MC_AKSCuster_AKSCuster_japaneast
                    kubernetes.azure.com/role=agent
                    kubernetes.io/hostname=aks-nodepool1-XXXXXXXX-vmss000000
                    kubernetes.io/role=agent
                    node-role.kubernetes.io/agent=
                    storageprofile=managed
                    storagetier=Premium_LRS
Annotations:        node.alpha.kubernetes.io/ttl: 0
                    volumes.kubernetes.io/controller-managed-attach-detach: true
CreationTimestamp:  Fri, 08 Nov 2019 06:44:42 +0000
Taints:             <none>
Unschedulable:      false
Conditions:
  Type                 Status  LastHeartbeatTime                 LastTransitionTime                Reason                       Message
  ----                 ------  -----------------                 ------------------                ------                       -------
  NetworkUnavailable   False   Fri, 08 Nov 2019 06:47:03 +0000   Fri, 08 Nov 2019 06:47:03 +0000   RouteCreated                 RouteController created a route
  MemoryPressure       False   Fri, 08 Nov 2019 10:07:38 +0000   Fri, 08 Nov 2019 06:44:42 +0000   KubeletHasSufficientMemory   kubelet has sufficient memory available
  DiskPressure         False   Fri, 08 Nov 2019 10:07:38 +0000   Fri, 08 Nov 2019 06:44:42 +0000   KubeletHasNoDiskPressure     kubelet has no disk pressure
  PIDPressure          False   Fri, 08 Nov 2019 10:07:38 +0000   Fri, 08 Nov 2019 06:44:42 +0000   KubeletHasSufficientPID      kubelet has sufficient PID available
  Ready                True    Fri, 08 Nov 2019 10:07:38 +0000   Fri, 08 Nov 2019 06:44:43 +0000   KubeletReady                 kubelet is posting ready status. AppArmor enabled
~ 中略 ~
  (Total limits may be over 100 percent, i.e., overcommitted.)
  Resource                       Requests    Limits
  --------                       --------    ------
  cpu                            200m (21%)  0 (0%)
  memory                         70Mi (3%)   170Mi (9%)
  ephemeral-storage              0 (0%)      0 (0%)
  attachable-volumes-azure-disk  0           0
Events:                          <none>

```

##ヘルプを参照
`$kubectl help` 
ヘルプの一覧を参照することが出来ます。

```
miyasaka@Azure:~/Understanding-K8s/chap02$ kubectl help
kubectl controls the Kubernetes cluster manager.

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

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        Documentation of resources
  get            Display one or many resources
  edit           Edit a resource on the server
  delete         Delete resources by filenames, 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, ReplicaSet, Replication Controller, or Job
  autoscale      Auto-scale a Deployment, ReplicaSet, or ReplicationController

Cluster Management Commands:
  certificate    Modify certificate resources.
  cluster-info   Display cluster info
  top            Display Resource (CPU/Memory/Storage) 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

Advanced Commands:
  diff           Diff live version against would-be applied version
  apply          Apply a configuration to a resource by filename or stdin
  patch          Update field(s) of a resource using strategic merge patch
  replace        Replace a resource by filename or stdin
  wait           Experimental: Wait for a specific condition on one or many resources.
  convert        Convert config files between different API versions
  kustomize      Build a kustomization target from a directory or a remote 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 or zsh)

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).
```

#リソースの削除
テストで構築しても、クラスターが稼働している間や ACR レジストリにコンテナーイメージデータを置いている間は課金が発生するので、作成したものは使用しない場合は削除しておきましょう。以下コマンドで今回作成したものの削除が可能です。

```terminal
$az group delete -name $AKS_RES_GROUP
$az group delete -name $AKS_RESOURCE_GROUP
$az ad sp delete --id=$(az ad ap show --id http://$SP_NAME --query appId --output tsv)
```

#参考
[kubectl Commands](https://kubernetes.io/docs/reference/kubectl/kubectl-cmds/)

[Azure Kubernetes Service (AKS)](https://azure.microsoft.com/ja-jp/services/kubernetes-service/)

[しくみがわかるKubernetes Azureで動かしながら学ぶコンセプトと実践知識](https://www.amazon.co.jp/%E3%81%97%E3%81%8F%E3%81%BF%E3%81%8C%E3%82%8F%E3%81%8B%E3%82%8BKubernetes-Azure%E3%81%A7%E5%8B%95%E3%81%8B%E3%81%97%E3%81%AA%E3%81%8C%E3%82%89%E5%AD%A6%E3%81%B6%E3%82%B3%E3%83%B3%E3%82%BB%E3%83%97%E3%83%88%E3%81%A8%E5%AE%9F%E8%B7%B5%E7%9F%A5%E8%AD%98-%E9%98%BF%E4%BD%90-%E5%BF%97%E4%BF%9D-ebook/dp/B07L94XGPY)