すぐにv0.10以降での日本語の記事が出てこなかったので備忘録として残しておく。
古いverでは仕様が違うようです。
TerraformのBackendとは
どのようにstate file(いわゆる.tfファイル)を管理し適用するか定義するもの。
Backend typeとしてAmazon S3だけでなくAzure Storage、Google Cloud Storageなどのパブリッククラウドのオブジェクトストレージサービスやetcdやconsulなどの分散KVSとして使えるもの等が用意されている。
使うメリットとしては、単純にstate fileをリモートで一括管理できるというだけでなく、backendによってはリモートでの実行も可能にしてくれるらしい。
参考: https://www.terraform.io/docs/backends/index.html
使ってみる
tfファイルの記述
terraform {
required_version = ">= 0.11.0"
backend "s3" {
bucket = "your-bucket-name" //e.g. terraform-state-bucket
key = "terraform.tfstate.aws" //この文字列でtfファイルが作られてS3に置かれる
region = "ap-northeast-1" //S3のリージョン
}
}
provider "aws" { // ProviderはAWSに限らずなんでも使える
access_key = "hoge"
secret_key = "hogehoge"
region = "${var.region}"
}
resource "hoge" "fuga" {
...
環境構築
terraform init
するとmoduleやpluginと共にbackendの設定も行われる。
-> % terraform init
Initializing modules...
- module.xxxxx
Initializing the backend...
Successfully configured the backend "s3"! Terraform will automatically
use this backend unless the backend configuration changes.
Initializing provider plugins...
- Checking for available provider plugins on https://releases.hashicorp.com...
- Downloading plugin for provider "aws" (1.6.0)...
The following providers do not have any version constraints in configuration,
so the latest version was installed.
To prevent automatic upgrades to new major versions that may contain breaking
changes, it is recommended to add version = "..." constraints to the
corresponding provider blocks in configuration, with the constraint strings
suggested below.
* provider.aws: version = "~> 1.6"
Terraform has been successfully initialized!
You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.
If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
問題なくbackendにS3が設定されると、terraform plan
やapply
やshow
などの実行の際にはS3に保存してあるtfファイルを見てくれる。
また、S3の中にまだtfファイルがない場合は、apply
した際にkeyで指定した文字列をファイル名にtfファイルを作ってくれる。
S3の中身をみてみる
こんな感じでS3の中にファイルが作られます。
まとめ
複数人でtfファイルを共有して使いたい場合に便利な方法がないか探していて試しましたが、非常に便利でした。