27
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

GKEクラスタを kubectl で扱えるよう登録する方法

Last updated at Posted at 2020-05-01

概要

kubectlを使ってGKEクラスタのマスターと通信出来るようにする。
具体的には kubectl config current-context で該当のGKEクラスタがセットされるようにする。

逆に言うと、クラスタを作成してもこの作業を行わなければ kubectl で操作できない。

前提

  • kubectl がインストールされている
  • gcloud がインストールされている

GKEでの方法です。EKSやAKSなどはまた別の手順があるので、そちらを参考にしてください。

手順

ざっくりいうと

  1. クラスターが存在する GCP プロジェクトに切り替えして、
  2. kubeconfigエントリを取得して、
  3. kubectl で扱えるかを確認する

だけ。

クラスターが存在する GCP プロジェクトに切り替え(gcloud)

gcloud config set project [ project_id ]

kubeconfigエントリの取得(GKEクラスタ未作成の場合)

gcloud コマンドを使ってクラスタを作成すると kubeconfig にkubeconfigエントリが格納される。

kubeconfigエントリは後述のコマンドから考えるにクラスターの認証情報と思われる。


$ gcloud container clusters create my-cluster # my-clusterはクラスタ名

Creating my-cluster...done
Fetching cluster endpoint and auth data.
kubeconfig entry generated for my-cluster

kubeconfigエントリの取得(GKEクラスタ作成済の場合)

すでに作成済のクラスタからkubeconfigエントリを習得する場合は以下のコマンド。


$ gcloud container clusters get-credentials my-cluster # my-clusterはクラスタ名

Fetching cluster endpoint and auth data.
kubeconfig entry generated for my-cluster.

このコマンドでkubeconfigエントリが生成される。

$ kubectl config get-contexts
CURRENT   NAME                                                                    CLUSTER                                                                 AUTHINFO                                                                NAMESPACE

*         project_asia-northeast1-a_my-cluster                          project_asia-northeast1-a_my-cluster                          project_asia-northeast1-a_my-cluster

kubectl で扱えるかを確認する

kubectl config current-contextで該当のGKEクラスタがセットされていることが確認できる。


$ kubectl config current-context
project_asia-northeast1-a_my-cluster

クラスタの切り替えはぶっちゃけ面倒なので kubectx を使うと楽。

$ brew install kubectx

kubectx だけを打つと、登録されているクラスタの一覧が表示される。

$ kubectx
project_asia-northeast1-a_my-cluster
project_asia-northeast1-b_your-cluster
project_asia-northeast1-c_our-cluster

いずれかを選択すると、スイッチ出来る。

$ kubectx project_asia-northeast1-c_our-cluster
Switched to context "project_asia-northeast1-c_our-cluster"

$ kubectx project_asia-northeast1-a_my-cluster
Switched to context "project_asia-northeast1-a_my-cluster"

参考

27
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?