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?

AWS 無料チュートリアルその13: S3 (Simple Storage Service) backend の state 管理

0
Posted at

AWSの無料枠で出来る範囲のチュートリアルを ChatGPT に示して頂いたので、試してみた経過を簡単にまとめてみました。
AWS等の実際の画面や操作はどんな感じか知りたい方を読者対象としているつもりです。

著者はAWS クラウドプラクティショナー、ソリューションアーキテクト アソシエイト という資格を取得済みで「AWSってなんぞや?」という概要を知識としてある程度理解しているが、実際にAWSの画面を触ったことが無いという状態でAWSのチュートリアルをこなしていくという状況です。

今回の内容としては、S3 (Simple Storage Service) backend の state 管理 を目標にしたいと思います。

🎯 まず結論

Terraformの状態ファイル(tfstate)をS3で管理する

これにより、

  • チーム開発できる
  • state破損リスク減る
  • 実務と同じ構成になる

🧠 構成イメージ

ローカル → S3 (state保存) → DynamoDB (ロック管理)

手順1: S3バケット作成

👉 まずは AWS コンソールで OK(Terraform でもできるが最初は手動推奨)

作成内容

  • バケット名:一意(例)
terraform-state-net4-xxxx
  • リージョン:
ap-northeast-1 (東京リージョン)

image.png

image.png

⚠️ 重要設定

👉 作成後

  • バージョニング ON
プロパティ → バージョニング → 有効化

👉 理由:

state壊れても戻せる

image.png

手順2: DynamoDB 作成 (ロック用)

作成内容

  • テーブル名:
terraform-lock
  • パーティションキー:
LockID (文字列)

image.png

image.png

👉 これで

複数人同時apply防止

手順3: Terraform に backend 設定

main.tf と同じディレクトリにbackend.tfを作り、追加👇

backend.tf
terraform {
  backend "s3" {
    bucket         = "terraform-state-net4-xxxx"  # ←自分の名前に変更
    key            = "terraform.tfstate"
    region         = "ap-northeast-1"
    dynamodb_table = "terraform-lock"
    encrypt        = true
  }
}

手順④:再初期化

terraform init

👉 すると

Do you want to copy existing state?

👉 必ず

yes

🎉 これで完成

🔍 確認方法

① S3を見る

👉 ファイルある

terraform.tfstate

② ローカル

👉 これが消える or 使われない

terraform.tfstate

image.png

💡 補足

❗ .gitignore に追加

terraform.tfstate
terraform.tfstate.backup

これはもうやってるのでOK 👍

🧠 仕組み理解

Before

ローカルにstate → 危険

After

S3にstate → 安全
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?