1
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?

More than 1 year has passed since last update.

terraform.tfstateファイルをS3で管理する

Last updated at Posted at 2022-04-12

terraform.tfstateファイルをS3で管理する時にError refreshing state: BucketRegionError: incorrect region, the bucket is not in 'ap-northeast-1' region at endpoint '' status code: 301, request id: , host id:というエラーが出て困った。その解決の手順を記録します。

初期化します。

terraform init

以下を記述して

provider.tf
provider "aws"{
      region = "ap-northeast-1"
      profile = "default"
}

terraform {
      required_version = "~> 1.1.7"
      required_providers {
            aws = {
                  source  = "hashicorp/aws"
                  version = "~> 4.0"
            }
      }
      # backend "s3" {
      #       bucket = "terraform-state-ymktmk"
      #       region = "ap-northeast-1"
      #       profile = "default"
      #       key = "terraform.tfstate"
      #       encrypt = true
      #       dynamodb_table = "terraform_state_lock"
      # }
}

resource "aws_s3_bucket" "terraform_state" {
      bucket = "<被らない名前で>"
      lifecycle {
            prevent_destroy = true
      }
      versioning {
            enabled = true
      }
}

resource "aws_dynamodb_table" "terraform_state_lock" {
      name = "<被らない名前で>"
      read_capacity = 1
      write_capacity = 1
      hash_key = "LockID"

      attribute {
      name = "LockID"
      type = "S"
      }
}

S3とDynamoDBを作成する

terraform apply

provider.tfのコメントアウトを元に戻して

terraform init

以下のように聞かれるのでyesを入力してEnterを押す。これでterraform.tfstateファイルをS3で管理することができるようになった。terraform applyでS3バケットを作成した後にterraform initでterraform.tfstateをS3で管理するようにしなければいけなかったっぽい。

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.
1
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
1
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?