Google CloudでTerraformを利用する

Google CloudでTerraformを利用するにあたり、基本的な部分について確認します。

Terraform、Gooble CloudそれぞれのGetting Start資料が下記です。

Terraform: Getting Started with the Google Provider

Google Cloud: Getting started with Terraform on Google Cloud

環境

  • Terraform v1.0.4
  • provider registry.terraform.io/hashicorp/google v3.79.0

Providerの指定

Google Cloud向けのProviderを利用します。Google Cloudの中の人と、HashiCorpの中の人でメンテナンスしてくれています。

Google Cloud Platform Provider

providerの指定方法。

terraform {
    required_version = ">= 1.0.4"
    required_providers {
        google = ">= 3.79.0"
    }
}

provider "google" {
    project = "{ project-name }"
    region = "asia-northeast1"
    zone = "asia-northeast1-a"
    credentials = file("./service-account-key.json")
}

Google Provider Configuration Reference

Google Cloudへの認証情報の利用

TerraformがGoogle CloudのAPIにアクセスする認証情報は、主に以下の2つを利用するようです。

  • gcloud auth application-default loginでの設定情報
  • サービスアカウントキーのファイル

gcloud auth application-default loginコマンドは、Google CLoudのClient Libraryを利用する時に参照される権限情報を管理するコマンドとなり、コマンドラインツールのgcloud用に権限設定をgcloud auth loginとは違うものとなります。

Application Default Credentials (ADC) provide a method to get credentials used in calling Google APIs. The gcloud auth application-default command group allows you to manage active credentials on your machine that are used for local application development. These credentials are only used by Google client libraries in your own application.

gcloud auth application-default

provider "google" {
    project = "{ project-name }"
    region = "asia-northeast1"
    zone = "asia-northeast1-a"
    credentials = file("./service-account-key.json")
}

上のテンプレートの例では、ダウンロードしてきたサービスアカウントのkeyファイルをcredentialsで参照しています。

Google Provider Configuration Reference - Authentication

Backend ConfigurationをCloud Storageのバケット上に置く

Backend Configurationとは、Terraformのstateファイルをリモート上で管理することで、複数人で同じリソースを管理できるようにする仕組みとなります。

Each Terraform configuration can specify a backend, which defines exactly where and how operations are performed, where state snapshots are stored, etc. Most non-trivial Terraform configurations configure a remote backend so that multiple people can work with the same infrastructure.

Backend Configuration

Cloud Storageを利用するためのコンフィグレーションです。

terraform {
  backend "gcs" {
    bucket  = { Bucket名 }
    prefix  = { Path }
  }
}

利用するバケットは、バージョニングを有効とすることを推奨されています。

Warning! It is highly recommended that you enable Object Versioning on the GCS bucket to allow for state recovery in the case of accidental deletions and human error.

Standard Backends - GCS

参考となるテンプレートたち

Google Cloudの人たちが作成したTerraform Moduleを公開してくれています。

cloud-foundation-toolkit/docs/terraform.md