04. Compute Engine
GCP の VM サービス Compute Engine。AWS EC2 相当ですが、マシンタイプの選択肢が多く、料金体系が独特(Sustained Use Discount や Spot VM)。
最小例
resource "google_compute_instance" "web" {
name = "vm-web-001"
machine_type = "e2-small"
zone = "asia-northeast1-a"
boot_disk {
initialize_params {
image = "ubuntu-os-cloud/ubuntu-2404-lts"
size = 20
type = "pd-balanced"
}
}
network_interface {
subnetwork = google_compute_subnetwork.public.id
access_config {} # External IP を付与(無いとプライベートのみ)
}
tags = ["http-server", "allow-ssh"] # Firewall の target_tags にマッチ
labels = local.common_labels
}
| マシンタイプ系列 | 用途 |
|---|---|
| e2-* | 汎用・低価格(推奨開始点) |
| n2-* | 汎用・高性能 |
| n2d-* | AMD ベース、コスパ良 |
| c3-* | 計算最適化 |
| t2d-* | Tau VM、汎用高コスパ |
| n1-* (旧) | レガシー、新規は非推奨 |
イメージの選択
image は <project>/<image-family-or-name> 形式。Google 公式が用意するファミリーを使うと最新パッチが自動適用。
data "google_compute_image" "ubuntu" {
family = "ubuntu-2404-lts"
project = "ubuntu-os-cloud"
}
resource "google_compute_instance" "web" {
boot_disk {
initialize_params {
image = data.google_compute_image.ubuntu.self_link
}
}
# ...
}
| OS | image family | project |
|---|---|---|
| Ubuntu 24.04 | ubuntu-2404-lts | ubuntu-os-cloud |
| Debian 12 | debian-12 | debian-cloud |
| Container-Optimized OS | cos-stable | cos-cloud |
| Windows Server 2022 | windows-2022 | windows-cloud |
Service Account の付与
VM に SA を割り当てると、その SA の権限で GCP API を叩けます(AWS IAM Instance Profile 相当)。
resource "google_service_account" "vm" {
account_id = "vm-web"
display_name = "Web VM Service Account"
}
resource "google_project_iam_member" "vm_storage_read" {
project = "myapp-prd"
role = "roles/storage.objectViewer"
member = "serviceAccount:${google_service_account.vm.email}"
}
resource "google_compute_instance" "web" {
# ...
service_account {
email = google_service_account.vm.email
scopes = ["cloud-platform"] # 細かい scope は IAM ロールで制御
}
}
起動スクリプト
resource "google_compute_instance" "web" {
# ...
metadata_startup_script = <<-EOT
#!/bin/bash
apt-get update
apt-get install -y nginx
systemctl enable --now nginx
echo "Hello from $(hostname)" > /var/www/html/index.html
EOT
metadata = {
enable-oslogin = "TRUE" # OS Login を強制(IAM ベースの SSH 制御)
block-project-ssh-keys = "TRUE"
}
}
OS Login 推奨
enable-oslogin = "TRUE" + IAM ロール roles/compute.osLogin 付与で、SSH キー管理が自動化されます。鍵を Project metadata に置く必要なし。
Preemptible / Spot VM
resource "google_compute_instance" "batch" {
name = "vm-batch-001"
machine_type = "e2-standard-4"
zone = "asia-northeast1-a"
scheduling {
preemptible = true
automatic_restart = false
provisioning_model = "SPOT" # 新方式(Preemptible より柔軟)
}
# ...
}
Spot VM は通常の 60-91% 割引。ただし AWS Spot と同じく 突然停止される可能性。バッチ・分散ジョブ向け。
Managed Instance Group (MIG)
複数 VM を 1 リソースで管理(AWS Auto Scaling Group 相当)。
resource "google_compute_instance_template" "web" {
name_prefix = "web-tpl-"
machine_type = "e2-small"
disk {
source_image = data.google_compute_image.ubuntu.self_link
auto_delete = true
boot = true
disk_type = "pd-balanced"
disk_size_gb = 20
}
network_interface {
subnetwork = google_compute_subnetwork.private.id
}
service_account {
email = google_service_account.vm.email
scopes = ["cloud-platform"]
}
metadata_startup_script = file("${path.module}/startup.sh")
tags = ["http-server"]
lifecycle {
create_before_destroy = true
}
}
resource "google_compute_region_instance_group_manager" "web" {
name = "mig-web"
region = "asia-northeast1"
base_instance_name = "web"
target_size = 3
version {
instance_template = google_compute_instance_template.web.self_link
}
auto_healing_policies {
health_check = google_compute_health_check.web.id
initial_delay_sec = 60
}
update_policy {
type = "PROACTIVE"
minimal_action = "REPLACE"
max_surge_fixed = 2
max_unavailable_fixed = 0
}
}
resource "google_compute_autoscaler" "web" {
name = "as-web"
zone = "asia-northeast1-a"
target = google_compute_region_instance_group_manager.web.id
autoscaling_policy {
max_replicas = 10
min_replicas = 3
cooldown_period = 60
cpu_utilization {
target = 0.6
}
}
}
VM 以外を先に検討
Web/API は Cloud Run、バッチは Cloud Run Jobs、Kubernetes 制御が必要なら GKE Autopilot。VM が必要なケースは「特殊 OS 設定」「ライセンスの都合」に限られます。