0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Terraform】Amazon S3でtfstateファイルを管理する

Last updated at Posted at 2025-07-06

はじめに

terraform構築したことない方は、ぜひ先にこちらも参照ください(^o^)★

tfstateとは

Terraformが管理するリソースの現在の状態を記録するファイルです。これはTerraformコマンドでリソースの反映等を行うたびに記録が上書きされます。
tfstateの保管先を定めていない場合はローカルで保管することになりますが、業務ではローカルで保管することは少ないでしょう。なので以下Amazon S3で保管するための手順を記します。

tfstateファイルをリモート保管

S3バケットを作成する

tfstateを保管するためのディレクトリとしてAmazonS3を利用します。
AWSコンソール画面からS3にて、バケットを作成します。今回は東京リージョンで作成します。

パブリックアクセスはすべてブロックにしましょう。
バケットのバージョニングはどちらでも大丈夫です。

image.png
image.png

tfstate保管先を設定

providers.tfを開き、以下を追加します。

providers.tf
terraform {
  required_providers {
    aws = {
      source = "hashicorp/aws"
      # version = "~> 5.92"
    }
  }
+  backend "s3" {
+    bucket = "作成したバケット名" 
+    region = "バケットが存在するリージョン"
+    key = "terraform.tfstate"
+  }

  required_version = ">= 1.2"
}

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

providers.tfを修正後、以下のコマンドを実施します。terraform applyでリソース反映後、指定したS3バケットにterraform.tfstateが自動的に作成されます。

> terraform init
> terraform apply

Terraform Configurationのルートディレクトリ(main.tf等が置いてあるディレクトリ)に既にterraform.tfstateファイルが存在し、tfstateファイルのS3バケットへのコピーのみを行いたい場合はterraform init(またはterraform init -upgrade)を実行します。

> 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

ローカルにあるterraform.tfstateをS3にコピーしますか?と聞かれるので、Enter a value: yesと答えるとS3バケットにローカルのterraform.tfstateがコピーされます。

Appendix

関連する記事

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?