前提
Terraform Install
$ brew install hashicorp/tap/terraform $ terraform --version Terraform v0.13.3
最新版にしたいとき
$ brew upgrade hashicorp/tap/terraform $ terraform --version Terraform v0.13.4
とはいえ、tfenv使うほうがいいのかなーと思ったりもする
追記 : tfenv のメモ
$ brew install tfenv $ tfenv install 0.8.0 # or latest $ tfenv use 0.8.0 $ echo 0.7.3 > .terraform-version # 引数なし tfenv install でそのバージョンがインストールされる
Create Service Account & Key
Terraform用のService Accountを作成して、JSONキーをダウンロードしておく
gcloud cli setup
# configの作成 $ gcloud config configurations create foobar-terraform # projectのset $ gcloud config set project foobar # accountのset $ gcloud config set account terraform@foobar.iam.gserviceaccount.com # 設定の確認 $ gcloud config configurations list # アカウントのactivate $ gcloud auth activate-service-account terraform@foobar.iam.gserviceaccount.com --key-file /path/to/foobar.json
json key を使わないでユーザでやる場合
$ gcloud auth application-default login
しましょう
tfstate用のGCS Bucket作成
gsutil mb -c regional -l asia-northeast1 gs://foobar-terraform-bucket
バージョニングの有効化
gsutil versioning set on gs://foobar-terraform-bucket
ライフサイクルの設定
$ cat foobar_terraform_bucket_lifecycle.json { "lifecycle": { "rule": [ { "action": { "type": "Delete" }, "condition": { "numNewerVersions": 3 } } ] } } $ gsutil lifecycle set "foobar_terraform_bucket_lifecycle.json" gs://foobar-terraform-bucket
export GOOGLE_CLOUD_KEYFILE_JSON
export GOOGLE_CLOUD_KEYFILE_JSON=/path/to/foobar.json export GOOGLE_APPLICATION_CREDENTIALS=$GOOGLE_CLOUD_KEYFILE_JSON
Write main.tf
provider "google" { project = "foobar" region = "asia-northeast1" zone = "asia-northeast1-a" } terraform { backend "gcs" { bucket = "foobar-terraform-bucket" } }
init
$ terraform init $ terraform plan $ terraform apply
tfstateがgcsに上がってる
$ gsutil ls gs://foobar-terraform-bucket/ gs://foobar-terraform-bucket/default.tfstate
Create Service Account
$ cat serviceaccount.tf resource "google_service_account" "bq_test_user" { account_id = "bq-test-user" display_name = "bq-test-user" } resource "google_project_iam_member" "bq_test_user" { count = length(var.bq_test_roles) role = element(var.bq_test_roles, count.index) member = "serviceAccount:${google_service_account.bq_test_user.email}" } variable "bq_test_roles" { default = [ "roles/bigquery.user", "roles/bigquery.jobUser" ] }
$ terraform fmt $ terraform plan $ terraform apply
tips
- module の upgrade
- terraform init -upgrade