anpanman
Published on

Terraform 新區域部署說明書(前置作業)

Terraform 新區域部署說明書(前置作業)

1️⃣ 前置條件

  • 已安裝 Terraform
  • 已設定好 AWS CLI,並有一個可用 profile 或憑證
  • 已有原始 Terraform code

2️⃣ 在新區域建立 Terraform State 用的資源

2.1 建 S3 Bucket

aws s3api create-bucket \
  --bucket my-terraform-state-bucket-apne2 \
  --region ap-northeast-2 \
  --create-bucket-configuration LocationConstraint=ap-northeast-2

⚠️ 注意:bucket 名稱全域唯一,每個 region 要建新的 bucket

2.2 建 DynamoDB Lock Table(選用)

aws dynamodb create-table \
  --table-name terraform-locks \
  --attribute-definitions AttributeName=LockID,AttributeType=S \
  --key-schema AttributeName=LockID,KeyType=HASH \
  --billing-mode PAY_PER_REQUEST \
  --region ap-northeast-2

用於多人人員同時操作時鎖定 state,避免衝突


3️⃣ 建立或更新 AWS Profile(如果有新的帳號或憑證)

編輯 ~/.aws/credentials

[new-aws-profile]
aws_access_key_id = AKIAxxxxxxx
aws_secret_access_key = xxxxxxxxx
region = ap-northeast-2

或用 SSO 設定:

[profile new-aws-profile]
sso_start_url = https://d-123.awsapps.com/start
sso_region = ap-northeast-1
sso_account_id = 123456789012
sso_role_name = AdministratorAccess
region = ap-northeast-2

4️⃣ 修改 Terraform Backend 設定

main.tfbackend.tf 添加 / 修改:

terraform {
  backend "s3" {
    bucket         = "my-terraform-state-bucket-apne2"   # 新 S3 bucket
    key            = "envs/prod/terraform.tfstate"       # state 檔在 bucket 路徑
    region         = "ap-northeast-2"                    # bucket 所在區域
    dynamodb_table = "terraform-locks"                  # lock table
    profile        = "new-aws-profile"                  # AWS profile
  }
}

這告訴 Terraform:「state 要存在這個新的 bucket,用這個 profile 連 AWS」


5️⃣ 初始化 Terraform

terraform init -reconfigure

5.1 Terraform 互動提示

  • 如果 backend 有變動,Terraform 會問:

    Terraform detected that the backend type changed. Do you want to migrate your existing state to the new backend?
    
  • yes 以建立新的 backend 並遷移 state

  • 如果只想初始化新的空 state,也可以選 no

這就是 Terraform 的互動式提示,你不用手動搬 state,也不用猜設定


6️⃣ 遷移舊 state(如果需要)

如果要把舊區域的 state 搬到新 bucket:

terraform init -migrate-state

7️⃣ 部署資源

terraform plan
terraform apply

這樣就會在新區域部署跟舊區域一模一樣的資源


🔑 小提醒

  1. S3 bucket 名稱全域唯一,每個 region 要新建
  2. profile 要確保有足夠權限在新區域建資源
  3. 如果多人共用,建議一定用 DynamoDB lock table
  4. terraform init -reconfigure 是必須的,否則 Terraform 仍會用舊 backend