はじめに
GCPを触り始めて、Terraformの存在を知ったので使ってみました。
Terraform
https://www.terraform.io/intro/index.html
インフラ構築の管理ツール
Terraform インストール
今回は、windows7の自端末にインストールします。
といっても、バイナリをダウンロードするだけです。
現在最新の 0.11.7
Windows(64bit)版をダウンロード
ダウンロードしたzipを解凍
解凍後の以下の実行ファイル
terraform.exe
適当なフォルダを作成して中に格納
GCP事前準備
1:新しいプロジェクト作成
2:サービスアカウント作成
[IAMと管理]→[サービスアカウント]
[サービスアカウントを作成]
※新しい秘密鍵の提供にチェック
キーのタイプはJSON
3:ダウンロードしたJSONファイルを先程作成したフォルダに格納
tfファイル準備
TFファイルとは、terraformよりインフラを構築するための設定ファイル
役割ごとにファイルを分割することで汎用的に運用できる
まずは、GCPの接続情報を渡すために以下のtfファイルを作成
// GCP provider
provider "google" {
credentials = "${file("key\\XXXXXXXXXX.json")}"
project = "XXXXXXX-999999"
region = "us-east1"
}
・credentialsはGCP認証鍵ファイルパス
後述しますが、keyフォルダ配下に配置したJSONを相対パスで参照
\はエスケープする必要あります。\\
・projectは認証鍵ファイル内に記載されている[project_id] ★要注意
GCPコンソールで表示されているProject名では動かず、ここでハマった。。。
次に作成するインスタンス用のtfファイル
今回はTerraform検証のため、GCPにはシンプルにインスタンスを1つ作成します。
resource "google_compute_instance" "terraform-test" {
name = "terraform-test"
machine_type = "f1-micro"
zone = "us-east1-c"
description = "gcp-terraform-test"
tags = ["terraform-test"]
boot_disk {
initialize_params {
image = "XXXXXXXXXXXXXXXX"
}
}
network_interface {
network = "default"
access_config {
// Ephemeral IP
}
}
service_account {
scopes = ["userinfo-email", "compute-ro", "storage-ro", "monitoring"]
}
}
・boot_disk - initialize_params - imageはお好みで
今回は過去に作ったcentos7のlampもどきのimageを使用しました。
フォルダ構成
terraform/
├ terraform.exe
├ key/
│ └ XXXXXXXXXX.json
└ gcp/
├ gcp_provider.tf
└ gcp_instances.tf
Terraform実行
コマンドプロンプト起動
cd 対象フォルダ
terraform init gcp
・・・
terraform plan gcp
・・・
terraform apply gcp
・・・
Plan: 1 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
[yes]入力
・・・
google_compute_instance.terraform-test: Still creating... (10s elapsed)
google_compute_instance.terraform-test: Creation complete after 13s (ID: terraform-test)
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
出来上がり
GCPコンソールから確認すると作ったインスタンスが起動しています。
さいごに
project_idでハマって3時間くらいかかったけど、出来てヨカタ
次はansible