🎉

【Terraform】tfstateファイルをS3で管理しよう

2025/01/10に公開

複数人で Terraform を使う際にtfstate ファイルの管理に悩みます。

ローカルで管理するには無理があるし、

git だとコンフリクトするとめんどう

上記の理由から、S3 で管理する方法が候補になるかと。

そこで、今回はtfstate ファイルを S3 で管理できるようにしていきます。

やってみる

tfstate を保存する S3 バケットを作成

main.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.16"
    }
  }

  required_version = ">= 1.2.0"
}

provider "aws" {
  region  = "ap-northeast-1"
}

# S3バケットの定義
resource "aws_s3_bucket" "terraform_state" {
  # バケット名は一意の必要があるので、bucketの値は各自変更してください
  bucket = "terraform-state-hisui"
}

# バージョニング設定
# tfstateファイルを任意の状態に戻せるように有効にしておく
resource "aws_s3_bucket_versioning" "terraform_state" {
  bucket = aws_s3_bucket.terraform_state.id

  versioning_configuration {
    status = "Enabled"
  }
}

次のコマンドを実行していき、S3 を作成します

1. terraform init
2. terraform plan
3. terraform apply -auto-approve

AWS コンソールで確認してみます。

無事作成できました

tfstate の保存先を S3 へ変更

main.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.16"
    }
  }

  required_version = ">= 1.2.0"

+  # tfstateの保存先
+  backend "s3" {
+    bucket = "terraform-state-hisui" # 作成したS3バケット
+    region = "ap-northeast-1"
+    # バケット内の保存先
+    # 適宜変更してください
+    key = "test/terraform.tfstate"
+    encrypt = true
+  }
}

provider "aws" {
  region  = "ap-northeast-1"
}

# S3バケットの定義
resource "aws_s3_bucket" "terraform_state" {
  # バケット名は一意の必要があるので、bucketの値は各自変更してください
  bucket = "terraform-state-hisui"
}

# バージョニング設定
# tfstateファイルを任意の状態に戻せるように有効にしておく
resource "aws_s3_bucket_versioning" "terraform_state" {
  bucket = aws_s3_bucket.terraform_state.id

  versioning_configuration {
    status = "Enabled"
  }
}

backend の設定をしたので、terraform init を実行します

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

 // ローカルのtfstateファイルをS3へコピーするか聞かれているので、「yes」
  Enter a value: yes


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

tfstate ファイルが S3 にコピーされているか確認します

コピーされていますねー

これで完了です

参考

https://qiita.com/tsukakei/items/2751e245e38c814225f1

Discussion