tfstateをS3で管理する

チーム開発をする際、tfstateがローカルにあると、都度都度applyする度にtfstateをgithubにアップしたりして面倒。誰かがアップし忘れるとまた面倒。。ということで、tfstateをS3でバックエンド管理することでtfstateを共有でき、何もしなくても最新の状態が保たれます。通常はtfstateはバックアップファイルが作成されますが、S3でバックエンド管理する場合は、S3のバージョン管理機能を使用するため、バックアップファイルを管理する必要はありません。 それでは手順にうつります。

1. tfstate用のS3バケットを作成し、バージョニングを有効にする

バケット名:aws.sample.tfstate

2. terraform.tfファイルを作成し、S3でのbackend管理設定を入れる

以下の様に作成する

▼ terraform.tf

terraform.tf

terraform {
  backend "s3" {
    bucket = "aws.sample.tfstate"
    key    = "ap-northeast-1/terraform/terraform.tfstate"
    region = "ap-northeast-1"
  }
}

3. terraform init でbackend設定を読み込ませる

以下の通りinitで初期化処理をし「Enter a value」でyesと打てばbackend設定が反映される。「Terraform has been successfully initialized!」と表示されていれば成功。

$ terraform init

Initializing the backend...
Do you want to copy existing state to the new backend?
  Pre-existing state was found while migrating the previous "local" backend to the
  newly configured "s3" backend. No existing state was found in the newly
  configured "s3" backend. Do you want to copy this state to the new "s3"
  backend? Enter "yes" to copy and "no" to start with an empty state.

  Enter a value: yes


Successfully configured the backend "s3"! Terraform will automatically
use this backend unless the backend configuration changes.

Initializing provider plugins...

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 = "~> 2.44"

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.
$ 

こんなに簡単に導入できるので、全ての案件に設定したいものです。