When it comes to real-world situation, we have multiple environments. Beside the variable files we talked in the last blog, Terraform also provides us to manage multiple states. First it doesn't mean multiple state files in the same folder or something along those lines, but the multiple storage for each state file. This is called "Backend".

Backend for Terraform defines the place we keep the state files. By default it is the local storage, our harddrives. Terraform supports on-cloud solution for this scenario. Today we're gonna use of course Google Cloud Storage. For all available solutions please click the doc below.

Backend Type: gcs | Terraform | HashiCorp Developer
Terraform can store the state remotely, making it easier to version and work with in a team.

Syntax

The keyword of this is backend and we can define it to use Google Cloud Storage as a backend like this.

terraform {
  backend "gcs" {
    bucket = "<bucket_name>"
    prefix = "<path_prefix>"
  }
}

Different backend requires different attributes that we can check on the doc above.

We need to create that bucket first, Terraform can use it to store the state files there.


Set the ball rolling

Now let's see how we can make it in real case.

Create backend.tf

We will create a new file for the backend.

This means our state files will be in gs://bluebirz-terraform-backend-bucket/terraform/state/.

Init

If we terraform init successfully we can see the message of backend "gcs" showing.

Otherwise, we need to re-initial. It could happen from changing backend after first initialization.

Apply

Assume validate and plan are done completely, we can apply the changes.

And see the result. There should be a new bucket from our tf script.

We can see the state file in the backend bucket have a state of the resource we create which is the new bucket, bluebirz_bucket_test1. Terraform just move the state file from local to the bucket we defined.


Same backend, different script

For some cases, if we have other tf scripts but use the same backend, it means we are changing the existing resources instead of create a new one.

For example, I create a new folder named "another_folder" and init.

Also prepare the tf scripts there. However the scripts are changed for only the bucket name from "bluebirz_bucket_test1" to "bluebirz_bucket_test2". You can see the plan showing the existing bucket will be replaced instead of being created.


We can apply this scenario for our work in order to efficiently manage the services and infrastures in various environments.