
terraform.tfstate.
Local State Storage:
.tfstate extension.Remote State Storage Benefits:
plan or apply command.How to Store Terraform State Remotely in a Cloud Storage Bucket:
google_storage_bucket resource to a Terraform configuration file (e.g., main.tf).US for a multi-region bucket. You can adjust the location as needed.terraform apply to create the Cloud Storage bucket.backend.tf and add the backend configuration, ensuring the bucket name matches your newly created bucket.terraform init to configure the backend. Terraform will detect the existing local state file and prompt you to copy it to the remote backend.yes when prompted.terraform init, Terraform will pull the latest state from the Cloud Storage bucket and push updates after each command.
State File Example:
Use Remote State for Team Environments:
Prevent State File Exposure:
.gitignore: To avoid committing state files to source control, add Terraform state files to .gitignore.Avoid Storing Secrets in State Files:
Encrypt State Files:
Avoid Manual Modification of Terraform State:
Write a main.tf file as below
json
provider "google" {
project = "<PROJECT ID>"
region = "us-west1"
}
resource "google_storage_bucket" "test-bucket-for-state" {
name = "<PROJECT ID>"
location = "US" # Replace with EU for Europe region
uniform_bucket_level_access = true
}
terraform {
backend "local" {
path = "terraform/state/terraform.tfstate" # Add a local backend
}
}

update the main.tf as below
provider "google" {
project = "qwiklabs-gcp-03-9947eda395a5"
region = "us-west1"
}
resource "google_storage_bucket" "test-bucket-for-state" {
name = "qwiklabs-gcp-03-9947eda395a5"
location = "US" # Replace with EU for Europe region
uniform_bucket_level_access = true
}
terraform {
backend "gcs" { # Create a remote state file
bucket = "qwiklabs-gcp-03-9947eda395a5"
prefix = "terraform/state"
}
}
Run terraform init -migrate-state
Now you can see your state file is uploaded on the bucket you made
The terraform refresh command is used to reconcile the state Terraform knows about (via its state file) with the real-world infrastructure. This can be used to detect any drift from the last-known state and to update the state file. This does not modify infrastructure, but does modify the state file. If the state is changed, this may cause changes to occur during the next plan or apply.
<- 수동으로 update 상황 가져오기.
terraform {
backend "local" {
path = "terraform/state/terraform.tfstate"
}
}
run terraform init -migrate-state
update the main.tf
resource "google_storage_bucket" "test-bucket-for-state" {
name = "qwiklabs-gcp-03-9947eda395a5"
location = "US" # Replace with EU for Europe region
uniform_bucket_level_access = true
force_destroy = true
}
run terraform apply
run terraform destroy