【GCP】TerraformでVM仮想マシンを作成してみた

【GCP】TerraformでVMインスタンスを作成してみた
やること
・TerraformでGCPにリソースを作成する
作成するリソース
・VPC
・サブネット
・ファイアウォールルール
・VMインスタンス
前提
・Windows11、PowerShellを利用
・terraformがインストールされていること
実践!
1.サービスアカウント作成
1-1.GCP - IAM - サービスアカウント
1-2「サービスアカウントを作成」

1-3.下記を入力
サービスアカウント名:test12345
サービスアカウントID:test12345(default)
サービスアカウントの説明:空白

1-4.「完了」
![]()
2.鍵発行
2-1.GCP - IAM - サービスアカウント
2-2.作成したサービスアカウントの「…」-「鍵を管理」

2-3.「キーを追加」-「新しい鍵を作成」

2-4.キーのタイプを「JSON」を選択し、「作成」、ローカルに保存

3.環境変数に鍵を登録
3-1.PowerShellを起動し、下記を実行
※これは一時的な設定のため、恒久的に使用したい場合はシステムの設定から登録要
> $env:GOOGLE_APPLICATION_CREDENTIALS="<鍵のファイルパス>"
> $env:GOOGLE_APPLICATION_CREDENTIALS="C:\xxxx\trusty-stack-xxxxx-f167e214744a.json"
4.サービスアカウントに権限付与
4-1.GCP - IAM

4-2.作成したサービスアカウントの鉛筆マークを選択

4-3.ロールに「Compute 管理者(compute.admin)」と、「サービス アカウント ユーザー(iam.serviceAccountUser)」を付与

4-4.「保存」

5.コード作成
5-1.下記ファイルを作成
main.tf
※GCPプロジェクトIDは自分の環境に合わせて変更する。
provider "google" { project = var.project_id # GCPプロジェクトID region = var.region # GCPリージョン(例: asia-northeast1) zone = var.zone # GCPゾーン(例: asia-northeast1-a) } # ネットワークの作成 resource "google_compute_network" "vpc_network" { name = "example-vpc" } # サブネットの作成 resource "google_compute_subnetwork" "subnet" { name = "example-subnet" ip_cidr_range = "10.0.0.0/24" network = google_compute_network.vpc_network.self_link region = var.region } # ファイアウォールルールの作成 resource "google_compute_firewall" "default" { name = "example-firewall" network = google_compute_network.vpc_network.name allow { protocol = "tcp" ports = ["22", "80", "443"] # SSH、HTTP、HTTPSを許可 } source_ranges = ["0.0.0.0/0"] # すべてのIPアドレスを許可(セキュリティ上注意!) target_tags = ["web-server"] # ターゲットVMにタグを適用する } # VMインスタンスの作成 resource "google_compute_instance" "vm_instance" { name = "example-vm" machine_type = "n1-standard-1" # マシンタイプ(CPU、メモリ構成) zone = var.zone boot_disk { initialize_params { image = "debian-cloud/debian-11" # OSイメージ size = 10 # ディスクサイズ(GB) } } network_interface { network = google_compute_network.vpc_network.self_link subnetwork = google_compute_subnetwork.subnet.self_link access_config { # 必須: 外部IPアドレスを割り当てる(インターネットアクセス可能にする) } } tags = ["http-server", "https-server"] metadata = { ssh-keys = "terraform:ssh-rsa AAAAB3..." # SSH公開鍵(任意) } }
variables.tf
variable "project_id" { description = "trusty-stack-xxxxxx" type = string } variable "region" { description = "GCPリージョン" default = "asia-northeast1" type = string } variable "zone" { description = "GCPゾーン" default = "asia-northeast1-a" type = string }
terraform.tfvars
project_id = "trusty-stack-xxxxxx" # GCPプロジェクトIDを指定 region = "asia-northeast1" # リージョンを指定 zone = "asia-northeast1-a" # ゾーンを指定
6.Terraform実行
6-1.PowerShellで下記を実行
> terraform init > terraform plan > terraform apply
> terraform apply
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated
with the following symbols:
+ create
Terraform will perform the following actions:
# google_compute_firewall.default will be created
+ resource "google_compute_firewall" "default" {
+ creation_timestamp = (known after apply)
+ destination_ranges = (known after apply)
+ direction = (known after apply)
+ enable_logging = (known after apply)
+ id = (known after apply)
+ name = "example-firewall"
+ network = "example-vpc"
+ priority = 1000
+ project = "trusty-stack-xxxxxx"
+ self_link = (known after apply)
+ source_ranges = [
+ "0.0.0.0/0",
]
+ target_tags = [
+ "web-server",
]
+ allow {
+ ports = [
+ "22",
+ "80",
+ "443",
]
+ protocol = "tcp"
}
}
# google_compute_instance.vm_instance will be created
+ resource "google_compute_instance" "vm_instance" {
+ can_ip_forward = false
+ cpu_platform = (known after apply)
+ creation_timestamp = (known after apply)
+ current_status = (known after apply)
+ deletion_protection = false
+ effective_labels = {
+ "goog-terraform-provisioned" = "true"
}
+ id = (known after apply)
+ instance_id = (known after apply)
+ label_fingerprint = (known after apply)
+ machine_type = "n1-standard-1"
+ metadata = {
+ "ssh-keys" = "terraform:ssh-rsa AAAAB3..."
}
+ metadata_fingerprint = (known after apply)
+ min_cpu_platform = (known after apply)
+ name = "example-vm"
+ project = "trusty-stack-xxxxxx"
+ self_link = (known after apply)
+ tags = [
+ "http-server",
+ "https-server",
]
+ tags_fingerprint = (known after apply)
+ terraform_labels = {
+ "goog-terraform-provisioned" = "true"
}
+ zone = "asia-northeast1-a"
+ boot_disk {
+ auto_delete = true
+ device_name = (known after apply)
+ disk_encryption_key_sha256 = (known after apply)
+ kms_key_self_link = (known after apply)
+ mode = "READ_WRITE"
+ source = (known after apply)
+ initialize_params {
+ image = "debian-cloud/debian-11"
+ labels = (known after apply)
+ provisioned_iops = (known after apply)
+ provisioned_throughput = (known after apply)
+ resource_policies = (known after apply)
+ size = 10
+ type = (known after apply)
}
}
+ network_interface {
+ internal_ipv6_prefix_length = (known after apply)
+ ipv6_access_type = (known after apply)
+ ipv6_address = (known after apply)
+ name = (known after apply)
+ network = (known after apply)
+ network_ip = (known after apply)
+ stack_type = (known after apply)
+ subnetwork = (known after apply)
+ subnetwork_project = (known after apply)
+ access_config {
+ nat_ip = (known after apply)
+ network_tier = (known after apply)
}
}
}
# google_compute_network.vpc_network will be created
+ resource "google_compute_network" "vpc_network" {
+ auto_create_subnetworks = true
+ delete_default_routes_on_create = false
+ gateway_ipv4 = (known after apply)
+ id = (known after apply)
+ internal_ipv6_range = (known after apply)
+ mtu = (known after apply)
+ name = "example-vpc"
+ network_firewall_policy_enforcement_order = "AFTER_CLASSIC_FIREWALL"
+ numeric_id = (known after apply)
+ project = "trusty-stack-xxxxxx"
+ routing_mode = (known after apply)
+ self_link = (known after apply)
}
# google_compute_subnetwork.subnet will be created
+ resource "google_compute_subnetwork" "subnet" {
+ creation_timestamp = (known after apply)
+ external_ipv6_prefix = (known after apply)
+ fingerprint = (known after apply)
+ gateway_address = (known after apply)
+ id = (known after apply)
+ internal_ipv6_prefix = (known after apply)
+ ip_cidr_range = "10.0.0.0/24"
+ ipv6_cidr_range = (known after apply)
+ name = "example-subnet"
+ network = (known after apply)
+ private_ip_google_access = (known after apply)
+ private_ipv6_google_access = (known after apply)
+ project = "trusty-stack-xxxxxx"
+ purpose = (known after apply)
+ region = "asia-northeast1"
+ self_link = (known after apply)
+ stack_type = (known after apply)
+ subnetwork_id = (known after apply)
}
Plan: 4 to add, 0 to change, 0 to destroy.
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: yes
google_compute_network.vpc_network: Creating...
google_compute_network.vpc_network: Still creating... [10s elapsed]
google_compute_network.vpc_network: Still creating... [20s elapsed]
google_compute_network.vpc_network: Still creating... [30s elapsed]
google_compute_network.vpc_network: Still creating... [40s elapsed]
google_compute_network.vpc_network: Still creating... [50s elapsed]
google_compute_network.vpc_network: Creation complete after 56s [id=projects/trusty-stack-xxxxxx/global/networks/example-vpc]
google_compute_subnetwork.subnet: Creating...
google_compute_firewall.default: Creating...
google_compute_firewall.default: Still creating... [10s elapsed]
google_compute_subnetwork.subnet: Still creating... [10s elapsed]
google_compute_firewall.default: Creation complete after 13s [id=projects/trusty-stack-xxxxxx/global/firewalls/example-firewall]
google_compute_subnetwork.subnet: Still creating... [20s elapsed]
google_compute_subnetwork.subnet: Creation complete after 28s [id=projects/trusty-stack-xxxxxx/regions/asia-northeast1/subnetworks/example-subnet]
google_compute_instance.vm_instance: Creating...
google_compute_instance.vm_instance: Still creating... [10s elapsed]
google_compute_instance.vm_instance: Still creating... [20s elapsed]
google_compute_instance.vm_instance: Still creating... [30s elapsed]
google_compute_instance.vm_instance: Creation complete after 31s [id=projects/trusty-stack-xxxxxx/zones/asia-northeast1-a/instances/example-vm]
Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
6-2.VMインスタンスが作成されていることを確認
6-2-1.GCP - VMインスタンス

7.削除
7-1.PowerShellで下記を実行
> terraform destroy
> terraform destroy
google_compute_network.vpc_network: Refreshing state... [id=projects/trusty-stack-xxxxxx/global/networks/example-vpc]
google_compute_subnetwork.subnet: Refreshing state... [id=projects/trusty-stack-xxxxxx/regions/asia-northeast1/subnetworks/example-subnet]
google_compute_firewall.default: Refreshing state... [id=projects/trusty-stack-xxxxxx/global/firewalls/example-firewall]
google_compute_instance.vm_instance: Refreshing state... [id=projects/trusty-stack-xxxxxx/zones/asia-northeast1-a/instances/example-vm]
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated
with the following symbols:
- destroy
Terraform will perform the following actions:
# google_compute_firewall.default will be destroyed
- resource "google_compute_firewall" "default" {
- creation_timestamp = "2024-12-15T00:53:11.746-08:00" -> null
- destination_ranges = [] -> null
- direction = "INGRESS" -> null
- disabled = false -> null
- id = "projects/trusty-stack-xxxxxx/global/firewalls/example-firewall" -> null
- name = "example-firewall" -> null
- network = "https://www.googleapis.com/compute/v1/projects/trusty-stack-xxxxxx/global/networks/example-vpc" -> null
- priority = 1000 -> null
- project = "trusty-stack-xxxxxx" -> null
- self_link = "https://www.googleapis.com/compute/v1/projects/trusty-stack-xxxxxx/global/firewalls/example-firewall" -> null
- source_ranges = [
- "0.0.0.0/0",
] -> null
- source_service_accounts = [] -> null
- source_tags = [] -> null
- target_service_accounts = [] -> null
- target_tags = [
- "web-server",
] -> null
- allow {
- ports = [
- "22",
- "80",
- "443",
] -> null
- protocol = "tcp" -> null
}
}
# google_compute_instance.vm_instance will be destroyed
- resource "google_compute_instance" "vm_instance" {
- can_ip_forward = false -> null
- cpu_platform = "Intel Broadwell" -> null
- creation_timestamp = "2024-12-15T00:53:42.574-08:00" -> null
- current_status = "RUNNING" -> null
- deletion_protection = false -> null
- effective_labels = {
- "goog-terraform-provisioned" = "true"
} -> null
- enable_display = false -> null
- id = "projects/trusty-stack-xxxxxx/zones/asia-northeast1-a/instances/example-vm" -> null
- instance_id = "8333766214257158137" -> null
- label_fingerprint = "vezUS-42LLM=" -> null
- labels = {} -> null
- machine_type = "n1-standard-1" -> null
- metadata = {
- "ssh-keys" = "terraform:ssh-rsa AAAAB3..."
} -> null
- metadata_fingerprint = "19mHBTvsDRM=" -> null
- name = "example-vm" -> null
- project = "trusty-stack-xxxxxx" -> null
- resource_policies = [] -> null
- self_link = "https://www.googleapis.com/compute/v1/projects/trusty-stack-xxxxxx/zones/asia-northeast1-a/instances/example-vm" -> null
- tags = [
- "http-server",
- "https-server",
] -> null
- tags_fingerprint = "6smc4R4d39I=" -> null
- terraform_labels = {
- "goog-terraform-provisioned" = "true"
} -> null
- zone = "asia-northeast1-a" -> null
- boot_disk {
- auto_delete = true -> null
- device_name = "persistent-disk-0" -> null
- mode = "READ_WRITE" -> null
- source = "https://www.googleapis.com/compute/v1/projects/trusty-stack-xxxxxx/zones/asia-northeast1-a/disks/example-vm" -> null
- initialize_params {
- enable_confidential_compute = false -> null
- image = "https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-11-bullseye-v20241210" -> null
- labels = {} -> null
- provisioned_iops = 0 -> null
- provisioned_throughput = 0 -> null
- resource_manager_tags = {} -> null
- resource_policies = [] -> null
- size = 10 -> null
- type = "pd-standard" -> null
}
}
- network_interface {
- internal_ipv6_prefix_length = 0 -> null
- name = "nic0" -> null
- network = "https://www.googleapis.com/compute/v1/projects/trusty-stack-xxxxxx/global/networks/example-vpc" -> null
- network_ip = "10.0.0.2" -> null
- queue_count = 0 -> null
- stack_type = "IPV4_ONLY" -> null
- subnetwork = "https://www.googleapis.com/compute/v1/projects/trusty-stack-xxxxxx/regions/asia-northeast1/subnetworks/example-subnet" -> null
- subnetwork_project = "trusty-stack-xxxxxx" -> null
- access_config {
- nat_ip = "34.84.104.183" -> null
- network_tier = "PREMIUM" -> null
}
}
- scheduling {
- automatic_restart = true -> null
- min_node_cpus = 0 -> null
- on_host_maintenance = "MIGRATE" -> null
- preemptible = false -> null
- provisioning_model = "STANDARD" -> null
}
- shielded_instance_config {
- enable_integrity_monitoring = true -> null
- enable_secure_boot = false -> null
- enable_vtpm = true -> null
}
}
# google_compute_network.vpc_network will be destroyed
- resource "google_compute_network" "vpc_network" {
- auto_create_subnetworks = true -> null
- delete_default_routes_on_create = false -> null
- enable_ula_internal_ipv6 = false -> null
- id = "projects/trusty-stack-xxxxxx/global/networks/example-vpc" -> null
- mtu = 0 -> null
- name = "example-vpc" -> null
- network_firewall_policy_enforcement_order = "AFTER_CLASSIC_FIREWALL" -> null
- numeric_id = "2526712770682103343" -> null
- project = "trusty-stack-xxxxxx" -> null
- routing_mode = "REGIONAL" -> null
- self_link = "https://www.googleapis.com/compute/v1/projects/trusty-stack-xxxxxx/global/networks/example-vpc" -> null
}
# google_compute_subnetwork.subnet will be destroyed
- resource "google_compute_subnetwork" "subnet" {
- creation_timestamp = "2024-12-15T00:53:14.287-08:00" -> null
- gateway_address = "10.0.0.1" -> null
- id = "projects/trusty-stack-xxxxxx/regions/asia-northeast1/subnetworks/example-subnet" -> null
- ip_cidr_range = "10.0.0.0/24" -> null
- name = "example-subnet" -> null
- network = "https://www.googleapis.com/compute/v1/projects/trusty-stack-xxxxxx/global/networks/example-vpc" -> null
- private_ip_google_access = false -> null
- private_ipv6_google_access = "DISABLE_GOOGLE_ACCESS" -> null
- project = "trusty-stack-xxxxxx" -> null
- purpose = "PRIVATE" -> null
- region = "asia-northeast1" -> null
- self_link = "https://www.googleapis.com/compute/v1/projects/trusty-stack-xxxxxx/regions/asia-northeast1/subnetworks/example-subnet" -> null
- stack_type = "IPV4_ONLY" -> null
- subnetwork_id = 7989747339666598000 -> null
}
Plan: 0 to add, 0 to change, 4 to destroy.
Do you really want to destroy all resources?
Terraform will destroy all your managed infrastructure, as shown above.
There is no undo. Only 'yes' will be accepted to confirm.
Enter a value: yes
google_compute_firewall.default: Destroying... [id=projects/trusty-stack-xxxxxx/global/firewalls/example-firewall]
google_compute_instance.vm_instance: Destroying... [id=projects/trusty-stack-xxxxxx/zones/asia-northeast1-a/instances/example-vm]
google_compute_instance.vm_instance: Still destroying... [id=projects/trusty-stack-xxxxxx/zones/asia-northeast1-a/instances/example-vm, 10s elapsed]
google_compute_firewall.default: Still destroying... [id=projects/trusty-stack-xxxxxx/global/firewalls/example-firewall, 10s elapsed]
google_compute_firewall.default: Destruction complete after 13s
google_compute_instance.vm_instance: Still destroying... [id=projects/trusty-stack-xxxxxx/zones/asia-northeast1-a/instances/example-vm, 20s elapsed]
google_compute_instance.vm_instance: Still destroying... [id=projects/trusty-stack-xxxxxx/zones/asia-northeast1-a/instances/example-vm, 30s elapsed]
google_compute_instance.vm_instance: Still destroying... [id=projects/trusty-stack-xxxxxx/zones/asia-northeast1-a/instances/example-vm, 40s elapsed]
google_compute_instance.vm_instance: Still destroying... [id=projects/trusty-stack-xxxxxx/zones/asia-northeast1-a/instances/example-vm, 50s elapsed]
google_compute_instance.vm_instance: Destruction complete after 54s
google_compute_subnetwork.subnet: Destroying... [id=projects/trusty-stack-xxxxxx/regions/asia-northeast1/subnetworks/example-subnet]
google_compute_subnetwork.subnet: Still destroying... [id=projects/trusty-stack-xxxxxx/regions/asia-northeast1/subnetworks/example-subnet, 10s elapsed]
google_compute_subnetwork.subnet: Still destroying... [id=projects/trusty-stack-xxxxxx/regions/asia-northeast1/subnetworks/example-subnet, 20s elapsed]
google_compute_subnetwork.subnet: Destruction complete after 22s
google_compute_network.vpc_network: Destroying... [id=projects/trusty-stack-xxxxxx/global/networks/example-vpc]
google_compute_network.vpc_network: Still destroying... [id=projects/trusty-stack-xxxxxx/global/networks/example-vpc, 10s elapsed]
google_compute_network.vpc_network: Still destroying... [id=projects/trusty-stack-xxxxxx/global/networks/example-vpc, 20s elapsed]
google_compute_network.vpc_network: Still destroying... [id=projects/trusty-stack-xxxxxx/global/networks/example-vpc, 30s elapsed]
google_compute_network.vpc_network: Still destroying... [id=projects/trusty-stack-xxxxxx/global/networks/example-vpc, 40s elapsed]
google_compute_network.vpc_network: Still destroying... [id=projects/trusty-stack-xxxxxx/global/networks/example-vpc, 50s elapsed]
google_compute_network.vpc_network: Still destroying... [id=projects/trusty-stack-xxxxxx/global/networks/example-vpc, 1m0s elapsed]
google_compute_network.vpc_network: Destruction complete after 1m5s
Destroy complete! Resources: 4 destroyed.
感想
飲みすぎると次の日だるいよね。(´Д`)