Mac端末でGCPのCompute EngineをTerraformを使用して作成する

GCPを仕事で触る機会が増えたのでIaC(Infrastructure as Code)を実現するツールを試してみている。
今回Terraformを触ってみたので簡単な使用手順を残しておく。
なお、Cloud SDK(glcoud コマンド)はインストールされている前提で話を進める。

今回はCompute Engine(以下、CE)をTerraformを使って構築した。

MacにTerraformをインストール

Homebrewでインストールできる。

$ brew update
$ brew install terraform

バージョン確認できればインストールが完了。

$ terraform --version
Terraform v0.12.24

GCPプロジェクトへの認証設定

Terraformを実行しているのは手元のMac端末なので、GCPプロジェクトのサービスアカウントの認証用JSONファイルを環境変数として登録する。

$ export GOOGLE_APPLICATION_CREDENTIALS="/Users/hoge/terraform/project/credential.json"

Compute Engineの作成

main.tfを作成し、テスト用プロジェクトの内容を記述する。

provider "google" {
  project     = "{{PROJECT_ID}}"
  region      = "asia-northeast1"
  zone        = "asia-northeast1-b"
}

compute_instance.tfを作成し、作成するインフラ環境(今回の場合だとCE)の内容を記述していく。

resource "google_compute_instance" "default" {
  project      = "PROJECT_ID"
  name         = "terraform"
  machine_type = "n1-standard-1"
  zone         = "us-central1-a"

  boot_disk {
    initialize_params {
      image = "centos-7-v20200420"
    }
  }

  network_interface {
    network = "default"
    access_config {
    }
  }
}

初期化

$ terraform init

実行プランの確認

$ terraform plan

プランの適用

$ terraform apply

実行したプランの内容は terraform.tfstate に書き込まれる。
そして現在の状態を確認するには下記コマンドを実行。

$ terraform show

CEのインスタンス作成後に現在のプランを確認すると特に実行予定プランがないことが表示される。つまり設定したプランが適用済みである状態。

$ terraform plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.

google_compute_instance.default: Refreshing state... [id=projects/xxxxxxxxxxxxxx/zones/us-central1-a/instances/terraform]

------------------------------------------------------------------------

No changes. Infrastructure is up-to-date.

This means that Terraform did not detect any differences between your
configuration and real physical resources that exist. As a result, no
actions need to be performed.

また作成したインスタンスは下記コマンドで削除できる。

$ terraform destroy

参考

GCPインフラ構築自動化の道 part1 ~Terraform 導入編~

Terraform × GCP 入門

Getting Started with the Google Provider

カテゴリーGCP

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

19 + 5 =

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください