Terraform State

Managing Terraform state files and remote backends.

State Commands

terraform state list # list all resources in state
terraform state show aws_instance.web # show resource details
terraform state mv aws_instance.old aws_instance.new # rename resource
terraform state rm aws_instance.web # remove from state

Remote Backend (S3)

terraform {
    backend "s3" {
        bucket = "my-terraform-state"
        key = "prod/terraform.tfstate"
        region = "us-east-1"
        encrypt = true
        dynamodb_table = "terraform-locks"
    }
}

Remote Backend (GCS)

terraform {
    backend "gcs" {
        bucket = "my-terraform-state"
        prefix = "terraform/state"
    }
}

State Locking

# Force unlock (use carefully!)
terraform force-unlock LOCK_ID

# Import existing resource
terraform import aws_instance.web i-1234567890abcdef0