Google Cloud CLI

Table of Contents

  1. インストール
  2. 初期設定
    1. gcloud init
    2. 認証
    3. プロジェクト設定
  3. 名前付き構成(configurations)
  4. よく使う共通オプション
  5. API の有効化
  6. サブコマンド別の解説
  7. 参考リンク

Google Cloud CLI は Google Cloud のリソースを作成・管理するためのコマンドラインツールです。Google Cloud SDK に含まれており、プロジェクト管理からデプロイまで幅広い操作を行えます。

インストール

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# macOS(Homebrew)
brew install --cask google-cloud-sdk

# Linux(apt)
sudo apt-get install google-cloud-cli

# Linux(スクリプト)
curl https://sdk.cloud.google.com | bash
exec -l $SHELL

# バージョン確認
gcloud version

# コンポーネントの更新
gcloud components update

インストールガイド(公式)

初期設定

gcloud init

対話式でプロジェクト・リージョン・ゾーンを設定します。

1
2
3
4
5
# 対話式の初期設定(ブラウザで認証)
gcloud init

# 既存の設定をリセットして再初期化
gcloud init --console-only

gcloud init リファレンス

認証

1
2
3
4
5
6
7
8
9
10
11
12
# ユーザーアカウントでログイン(ブラウザが開く)
gcloud auth login

# サービスアカウントで認証
gcloud auth activate-service-account --key-file=credentials.json

# Application Default Credentials(ADC)の設定
# ローカル開発でクライアントライブラリが使う認証情報を設定
gcloud auth application-default login

# 現在の認証アカウントを確認
gcloud auth list

gcloud auth リファレンス

プロジェクト設定

1
2
3
4
5
6
7
8
9
# 現在のプロジェクトを設定
gcloud config set project PROJECT_ID

# 現在のプロジェクトを確認
gcloud config get project

# デフォルトリージョン・ゾーンを設定
gcloud config set compute/region asia-northeast1
gcloud config set compute/zone asia-northeast1-a

名前付き構成(configurations)

プロジェクトや認証情報のセットを切り替えて使えます。本番環境と開発環境の切り替えに便利です。

1
2
3
4
5
6
7
8
9
10
11
12
13
# 構成の一覧
gcloud config configurations list

# 新しい構成を作成
gcloud config configurations create dev
gcloud config set project my-dev-project
gcloud config set compute/region asia-northeast1

# 構成を切り替え
gcloud config configurations activate prod

# 構成を指定して実行(切り替え不要)
gcloud compute instances list --configuration=prod

gcloud config configurations リファレンス

よく使う共通オプション

オプション 説明
--project=PROJECT_ID プロジェクトを指定(デフォルト設定を上書き)
--format=json 出力形式を指定(jsonyamlcsvtable
--filter="EXPRESSION" 結果をフィルタリング
--quiet / -q 確認プロンプトをスキップ
--verbosity=debug デバッグ出力を有効化
--impersonate-service-account=SA サービスアカウントになりすまして実行
1
2
3
4
5
6
7
8
# JSON 形式で出力
gcloud compute instances list --format=json

# フィルタで絞り込み
gcloud compute instances list --filter="zone:asia-northeast1-a AND status=RUNNING"

# 特定のフィールドだけ取得
gcloud projects list --format="table(projectId, name, projectNumber)"

gcloud topic filters(公式)
gcloud topic formats(公式)

API の有効化

Google Cloud の各サービスは API を有効化してから使います。

1
2
3
4
5
6
7
8
9
# API を有効化
gcloud services enable run.googleapis.com
gcloud services enable container.googleapis.com

# 有効な API の一覧
gcloud services list --enabled

# 利用可能な API を検索
gcloud services list --available --filter="name:run"

gcloud services リファレンス

サブコマンド別の解説

参考リンク