小ネタ。
複数の k8s のマスターを kubectl で操作する場合にどのように操作対象のマスターを変えるという点について確認したのでメモ。
まとめ
-
~/.kube/config
の current-context を変えることで操作対象のマスターを変えている - context の変更は
kubectl config use-context
によって可能
環境
$ kubectl version
Client Version: version.Info{Major:"1", Minor:"10", GitVersion:"v1.10.3", GitCommit:"2bba0127d85d5a46ab4b778548be28623b32d0b0", GitTreeState:"clean", BuildDate:"2018-05-28T20:03:09Z", GoVersion:"go1.9.3", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"11+", GitVersion:"v1.11.5-eks-6bad6d", GitCommit:"6bad6d9c768dc0864dab48a11653aa53b5a47043", GitTreeState:"clean", BuildDate:"2018-12-06T23:13:14Z", GoVersion:"go1.10.3", Compiler:"gc", Platform:"linux/amd64"}
k8s のマスターは EKS を利用する。
マスターとの通信には認証が必要だが、この情報はデフォルトでは~/.kube/config
を利用する。(環境変数KUBECONFIG
で変えれる模様)
現状 kubectl を実行するとこんな感じ。
# 現在の context は eks-first-cluster
$kubectl config current-context
arn:aws:eks:ap-northeast-1:xxxx:cluster/eks-first-cluster
# ファイル上も同じ
$cat ~/.kube/config |grep current-context
current-context: arn:aws:eks:ap-northeast-1:323817733012:cluster/eks-first-cluster
# worker node が存在する
$kubectl get nodes
NAME STATUS ROLES AGE VERSION
ip-172-31-0-56.ap-northeast-1.compute.internal Ready <none> 4d v1.11.5
ip-172-31-19-51.ap-northeast-1.compute.internal Ready <none> 4d v1.11.5
ip-172-31-23-75.ap-northeast-1.compute.internal Ready <none> 4d v1.11.5
マスター情報を追加して context を変える
上記状態でマスター(eks-second-cluster)を別途作成し、kubectl で操作する。
~/.kube/config
への設定追加はaws eks update-kubeconfig --name cluster_name
で実施。
これによって~/.kube/config
に追記が実施され、kubectl によって操作するマスターが変わった。
より具体的には current-context が新規に作成したマスターになっていた。
# context が変わっている
$kubectl config current-context
arn:aws:eks:ap-northeast-1:xxx:cluster/eks-second-cluster
# config ファイルも変わっている
$cat ~/.kube/config |grep current-context
current-context: arn:aws:eks:ap-northeast-1:xxx:cluster/eks-second-cluster
# eks-second-cluster には worker node がない
$kubectl get nodes
No resources found.
操作したいクラスターを変えたい場合、kubectl config use-context
で変更出来る。
# context を変える
$kubectl config use-context arn:aws:eks:ap-northeast-1:xxx:cluster/eks-first-cluster
Switched to context "arn:aws:eks:ap-northeast-1:xxxx:cluster/eks-first-cluster".
$kubectl get nodes
NAME STATUS ROLES AGE VERSION
ip-172-31-0-56.ap-northeast-1.compute.internal Ready <none> 4d v1.11.5
ip-172-31-19-51.ap-northeast-1.compute.internal Ready <none> 4d v1.11.5
ip-172-31-23-75.ap-northeast-1.compute.internal Ready <none> 4d v1.11.5
なお、shell autocompletionを入れておくと kubectl config use-context
実行時に tab で設定変更可能な context が分かるので便利。
公式ドキュメントとしては以下辺りが参考になりそうなのであとで見ておく