Post

Let's try: Terraform part 3 - backend

Terraform also provides us to manage multiple states.

Let's try: Terraform part 3 - backend
In this series

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 check the doc at the link below.


Syntax

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

1
2
3
4
5
6
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.

init

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

reinit

Apply

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

apply

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

result

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.

gsutil cat


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.

init new folder

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.

validate new folder


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

This post is licensed under CC BY 4.0 by the author.