로컬 tfstate를 GCS(Google Cloud Storage)로 마이그레이션 해봅시다.

tfstate 파일을 복사해서 gcs에 업로드하면 안되고, backend 설정을 해야 합니다.

 

Prerequisite

  • 서비스 계정 생성 및 아래 Permission 추가 (Storage Admin Role 추가하는 걸로 대체 가능)
    • storage.buckets.create
    • storage.buckets.list
    • storage.objects.get
    • storage.objects.create
    • storage.objects.delete
    • storage.objects.update
  • json key 생성

 

Steps

terraform {
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "4.35.0"
    }
  }
}

provider "google" {
  project     = "terraform-gcp-362013"
  region      = "us-central1"
  zone        = "us-central1-a"
  credentials = "keys.json"
}

resource "random_id" "bucket_prefix" {
  byte_length = 8
}

resource "google_storage_bucket" "default" {
  name          = "${random_id.bucket_prefix.hex}-bucket-tfstate"
  force_destroy = false
  location      = "US"
  storage_class = "STANDARD"
  versioning {
    enabled = true
  }
}

output "bucket_name" {
  value = google_storage_bucket.default.name
}

먼저 main.tf 파일을 이렇게 구성합니다.

terraform init -> terraform apply 하면 랜덤한 prefix가 붙은 unique한 이름을 가진 storage bucket이 생성됩니다.

생성된 버킷 이름을 복사해서 backend 설정을 추가해줍니다.

 

terraform {
  # ...

  backend "gcs" {
    bucket = "7659799319461fd4-bucket-tfstate"
    prefix = "terraform/state"
  }
}

백엔드 설정을 위처럼 추가한 뒤 terraform init을 한번 더 해줍니다

 

❯ terraform init

Initializing the backend...
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 "gcs" backend. No existing state was found in the newly
  configured "gcs" backend. Do you want to copy this state to the new "gcs"
  backend? Enter "yes" to copy and "no" to start with an empty state.

  Enter a value: yes


Successfully configured the backend "gcs"! Terraform will automatically
use this backend unless the backend configuration changes.

Initializing provider plugins...
...

Terraform has been successfully initialized!

yes를 입력하면 현재 state가 gcs에 복사됩니다.

백엔드 설정은 .terraform/terraform.tfstate에 저장됩니다.

 

버킷에 들어가보면 백엔드 설정대로 tfstate가 복사된 것을 확인할 수 있습니다.

참고로 workspace 선택해도 default.tfstate를 무조건 생성하는 버그가 있다고 합니다 (https://github.com/hashicorp/terraform/issues/28497)

 

참고

 

Cloud Storage 버킷에 Terraform 상태 저장  |  Google Cloud

의견 보내기 Cloud Storage 버킷에 Terraform 상태 저장 알림 이 페이지를 개발자 프로필에 저장하여 중요 업데이트에 대한 알림을 받으세요. 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐

cloud.google.com

 

반응형

'Infra > terraform' 카테고리의 다른 글

Terraform 설치 및 GCP 연결  (0) 2022.09.03