Sobes.tech
Middle+

If you delete the state from the machine and upload it to the provider, will it be loaded during the terraform init command? Or what will happen in this case?

sobes.tech AI

Answer from AI

No, when running terraform init, the state will not be automatically uploaded to the machine after it has been deleted from the local disk and transferred to the provider.

terraform init primarily performs the following actions:

  • Initializes the backend that was configured for remote state storage (e.g., S3, Azure Blob Storage, Google Cloud Storage).
  • Downloads provider plugins specified in the configuration.
  • Downloads modules if they are used.

The local state file (terraform.tfstate) is deleted from the local machine. Terraform will only use the state stored in the configured backend.

What will happen:

  1. When running terraform init, Terraform reads the configuration and detects the presence of a configured backend.
  2. It initializes this backend, establishing a connection to the remote storage.
  3. No new local terraform.tfstate file will be created on the local machine. Terraform will work directly with the remote state.

In subsequent commands (terraform plan, terraform apply, terraform destroy), Terraform will access the remote backend to retrieve the current infrastructure state.

Example of S3 backend configuration:

# S3 backend configuration
terraform {
  backend "s3" {
    bucket = "my-terraform-state-bucket"  # S3 bucket name
    key    = "path/to/my/state.tfstate"    # Object key in the bucket
    region = "us-east-1"                  # S3 bucket region
    # Additional options, e.g., encryption, dynamodb_table for locks
  }
}

# Resource example
resource "aws_instance" "example" {
  ami           = "ami-0abcdef1234567890"
  instance_type = "t2.micro"

  tags = {
    Name = "example-instance"
  }
}