mcpField
G
gcp-compute

gcp-compute

github.com/bagelholeクラウド・DevOps1.2k331 回インストール23 週間前に更新
リポジトリ

gcp-compute について

Compute Engine を管理する GCP 運用担当者や開発者向けのコマンドラインガイドです。VM の作成やスケーリング、マネージドインスタンスグループ、スナップショット、トラブルシューティングを扱い、Terraform の設定例も掲載しています。

主な機能

  1. 01Compute Engine VM の作成と管理
  2. 02インスタンステンプレートとマネージドインスタンスグループの設定
  3. 03Spot VM でのワークロード実行
  4. 04ディスクスナップショットとスケジュールの作成
  5. 05Terraform の設定例
  6. 06一般的なトラブルシューティングの案内

活用シーン

  1. 01OS レベルの制御が必要なアプリケーションサーバーをデプロイ
  2. 02自動修復・自動スケーリングするインスタンスグループを構築
  3. 03機械学習トレーニング用の GPU VM を用意
  4. 04重要度の低いワークロードに Spot VM を使いコストを抑制

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/bagelhole/devops-security-agent-skills --skill gcp-compute

インストール後、Claude Code で/gcp-computeを入力して読み込まれたか確認します。

詳細

GCP Compute Engine

Google Cloud Platform で Compute Engine 仮想マシンをデプロイ、管理、スケーリングします。

使用する場面

  • GCP で Web サーバー、アプリケーションのバックエンド、バッチ処理ワークロードをデプロイする場合
  • OS レベルの完全な制御が必要なワークロードを実行する場合(Cloud Run や App Engine とは異なります)
  • ロードバランサーの背後で自動修復と自動スケーリングを行うマネージドインスタンスグループを作成する場合
  • ML トレーニングやレンダリングのパイプライン向けに、GPU を接続した VM をプロビジョニングする場合
  • プリエンプティブル VM またはスポット VM を使って、重要度の低いワークロードのコストを最適化する場合

前提条件

  • Google Cloud SDK(gcloud)がインストールされ、認証済みであること
  • Compute Engine API が有効になっている GCP プロジェクト
  • IAM ロール roles/compute.admin、またはインスタンス管理に必要な範囲のロール
gcloud auth list
gcloud config set project $PROJECT_ID
gcloud services enable compute.googleapis.com

マシンタイプのリファレンス

ファミリー例vCPUメモリ用途
E2e2-micro0.251 GB開発/テスト、マイクロサービス
E2e2-medium14 GB軽量な Web サーバー
N2n2-standard-4416 GB汎用的な本番環境
N2n2-highmem-8864 GBインメモリキャッシュ、データベース
C2c2-standard-161664 GB計算負荷の高い処理、HPC
# List machine types available in a zone
gcloud compute machine-types list --zones=us-central1-a --filter="name~'e2-'"

# Create a custom machine type (6 vCPUs, 24 GB RAM)
gcloud compute instances create custom-vm \
  --custom-cpu=6 --custom-memory=24GB \
  --zone=us-central1-a \
  --image-family=debian-12 --image-project=debian-cloud

インスタンスの作成

# Production instance with shielded VM and startup script
gcloud compute instances create web-server \
  --machine-type=e2-medium \
  --zone=us-central1-a \
  --image-family=debian-12 \
  --image-project=debian-cloud \
  --boot-disk-size=20GB \
  --boot-disk-type=pd-balanced \
  --tags=http-server,https-server \
  --labels=env=production,team=backend \
  --metadata=enable-oslogin=TRUE \
  --shielded-secure-boot \
  --shielded-vtpm \
  --shielded-integrity-monitoring

# Instance with a startup script and service account
gcloud compute instances create app-server \
  --machine-type=e2-standard-2 \
  --zone=us-central1-a \
  --image-family=ubuntu-2204-lts \
  --image-project=ubuntu-os-cloud \
  --boot-disk-size=50GB \
  --metadata-from-file=startup-script=startup.sh \
  --service-account=app-sa@${PROJECT_ID}.iam.gserviceaccount.com \
  --scopes=cloud-platform

# Instance with an additional data disk
gcloud compute instances create db-server \
  --machine-type=n2-highmem-4 \
  --zone=us-central1-a \
  --image-family=debian-12 --image-project=debian-cloud \
  --boot-disk-size=20GB \
  --create-disk=name=data-disk,size=200GB,type=pd-ssd,auto-delete=no

スタートアップスクリプトの例

#!/bin/bash
# startup.sh - runs on first boot and every reboot
set -euo pipefail
apt-get update && apt-get install -y nginx
systemctl enable nginx && systemctl start nginx
curl -X PUT -H "Metadata-Flavor: Google" \
  "http://metadata.google.internal/computeMetadata/v1/instance/guest-attributes/startup/status" \
  -d "complete"

インスタンステンプレートとマネージドインスタンスグループ

# Create an instance template
gcloud compute instance-templates create web-template \
  --machine-type=e2-medium \
  --image-family=debian-12 --image-project=debian-cloud \
  --boot-disk-size=20GB --tags=http-server \
  --metadata-from-file=startup-script=startup.sh

# Create a regional managed instance group (MIG) with health check
gcloud compute health-checks create http http-health-check \
  --port=80 --request-path=/healthz \
  --check-interval=10s --timeout=5s \
  --healthy-threshold=2 --unhealthy-threshold=3

gcloud compute instance-groups managed create web-mig \
  --template=web-template --size=3 \
  --region=us-central1 \
  --health-check=http-health-check --initial-delay=120

# Configure autoscaling
gcloud compute instance-groups managed set-autoscaling web-mig \
  --region=us-central1 \
  --min-num-replicas=2 --max-num-replicas=10 \
  --target-cpu-utilization=0.65 --cool-down-period=90

# Rolling update to a new template
gcloud compute instance-groups managed rolling-action start-update web-mig \
  --version=template=web-template-v2 \
  --region=us-central1 --max-surge=3 --max-unavailable=0

プリエンプティブル VM とスポット VM

# Spot VM (recommended over legacy preemptible)
gcloud compute instances create spot-worker \
  --machine-type=n2-standard-8 \
  --zone=us-central1-a \
  --image-family=debian-12 --image-project=debian-cloud \
  --provisioning-model=SPOT \
  --instance-termination-action=STOP

# Spot instance template for batch MIG
gcloud compute instance-templates create batch-template \
  --machine-type=n2-standard-4 \
  --image-family=debian-12 --image-project=debian-cloud \
  --provisioning-model=SPOT \
  --instance-termination-action=DELETE

スナップショットとイメージ

# Create a snapshot
gcloud compute disks snapshot web-server \
  --zone=us-central1-a \
  --snapshot-names=web-server-snap-$(date +%Y%m%d)

# Scheduled snapshot policy
gcloud compute resource-policies create snapshot-schedule daily-backup \
  --region=us-central1 --max-retention-days=14 \
  --daily-schedule --start-time=03:00

gcloud compute disks add-resource-policies web-server \
  --zone=us-central1-a --resource-policies=daily-backup

# Create a custom image from an instance
gcloud compute instances stop web-server --zone=us-central1-a
gcloud compute images create web-golden-image \
  --source-disk=web-server --source-disk-zone=us-central1-a \
  --family=web-server --labels=version=v1

Terraform の設定

resource "google_compute_instance" "web" {
  name         = "web-server"
  machine_type = "e2-medium"
  zone         = "us-central1-a"
  tags         = ["http-server", "https-server"]

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-12"
      size  = 20
      type  = "pd-balanced"
    }
  }

  network_interface {
    subnetwork = google_compute_subnetwork.main.id
    access_config {}
  }

  metadata_startup_script = file("${path.module}/startup.sh")

  service_account {
    email  = google_service_account.app.email
    scopes = ["cloud-platform"]
  }

  shielded_instance_config {
    enable_secure_boot          = true
    enable_vtpm                 = true
    enable_integrity_monitoring = true
  }
}

resource "google_compute_instance_template" "web" {
  name_prefix  = "web-"
  machine_type = "e2-medium"

  disk {
    source_image = "debian-cloud/debian-12"
    auto_delete  = true
    boot         = true
    disk_size_gb = 20
  }

  network_interface {
    subnetwork = google_compute_subnetwork.main.id
  }

  lifecycle { create_before_destroy = true }
}

resource "google_compute_region_instance_group_manager" "web" {
  name               = "web-mig"
  base_instance_name = "web"
  region             = "us-central1"

  version {
    instance_template = google_compute_instance_template.web.id
  }

  target_size = 3
  named_port { name = "http"; port = 80 }

  auto_healing_policies {
    health_check      = google_compute_health_check.http.id
    initial_delay_sec = 120
  }
}

resource "google_compute_region_autoscaler" "web" {
  name   = "web-autoscaler"
  region = "us-central1"
  target = google_compute_region_instance_group_manager.web.id

  autoscaling_policy {
    min_replicas    = 2
    max_replicas    = 10
    cooldown_period = 90
    cpu_utilization { target = 0.65 }
  }
}

一般的な操作

# SSH into an instance
gcloud compute ssh web-server --zone=us-central1-a

# List all instances with status
gcloud compute instances list \
  --format="table(name,zone,status,machineType.basename())"

# Stop / start / resize
gcloud compute instances stop web-server --zone=us-central1-a
gcloud compute instances set-machine-type web-server \
  --machine-type=e2-standard-4 --zone=us-central1-a
gcloud compute instances start web-server --zone=us-central1-a

# View serial port output (debug startup scripts)
gcloud compute instances get-serial-port-output web-server --zone=us-central1-a

トラブルシューティング

症状原因対処方法
インスタンスが STAGING のまま進まないクォータ超過またはリソースを利用できないgcloud compute project-info describe でクォータを確認します。別のゾーンを試してください
スタートアップスクリプトが実行されない構文エラーまたはメタデータキーの誤りシリアル出力を確認し、キーが startup_script ではなく startup-script であることを確認します
SSH 接続できないファイアウォールがポート 22 をブロックしている、または OS Login の設定に誤りがあるtcp:22 のファイアウォールルールを追加し、enable-oslogin メタデータを確認します
プリエンプションが頻繁に発生するゾーンのリソース逼迫アクションに STOP を指定したスポット VM を使い、MIG 内で複数のゾーンに分散します
ディスクの空き容量がないブートディスクが小さすぎるgcloud compute disks resize を使います。データディスクでは --storage-auto-increase を有効にします
MIG がインスタンスを修復しないヘルスチェックの設定に誤りがある、または初期待機時間が短すぎるヘルスチェックのパスが 200 を返すことを確認し、--initial-delay を長くします

関連するスキル

  • gcp-networking - Compute Engine 向けの VPC、ファイアウォールルール、ロードバランサー
  • terraform-gcp - Infrastructure as Code で Compute Engine リソースをプロビジョニング
  • gcp-gke - ワークロードに VM よりもコンテナが適している場合
  • gcp-cloud-sql - Compute Engine アプリケーションが接続するマネージドデータベース

コメント