使用S3对terraform.tfstate文件进行管理

在使用S3管理terraform.tfstate文件时,出现了Error refreshing state: BucketRegionError: 错误的地区,该存储桶不在’ap-northeast-1’地区的端点” status code: 301, request id: , host id:的问题,让人很困扰。下面记录解决此问题的步骤。

进行初始化。

terraform init

请以中文形式记录以下内容。

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

当被询问时,请输入”是”并按回车键。这样,就能够将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.
广告
将在 10 秒后关闭
bannerAds