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.