Terraform on GCP: Authentication and GCS Backend

Terraform on GCP: Authentication and GCS Backend Terraform allows us to carry out IaC (Infrastructure as Code) implementations. We can apply and destroy infrastructure in a fast and automated way. In order to perform these operations, one o

Source comparison and review notes
  • Automated pair-review warning (AI bilingual content review): Both sources demonstrate downloading a user-managed Service Account JSON key and placing it in the Terraform code repository under .gitignore; although they mention safer production alternatives, this credential-handling approach needs security review.

Terraform allows us to carry out IaC (Infrastructure as Code) implementations. We can apply and destroy infrastructure in a fast and automated way. In order to perform these operations, one of the fundamental Terraform files is the <terraform.tfstate> file.

What is State and what is it used for in Terraform?

Terraform needs to store the state of the infrastructure and its configuration. This “real world” information is stored in the file <terraform.tfstate>.

By storing the state of resources and their dependencies, Terraform can determine what changes it needs to apply to the existing infrastructure to reach the desired state defined in the code: the “desired state.”

This file stores information about the resources that Terraform has created or configured and is kept up to date as infrastructure changes occur under the tool’s radar.

It is crucial to handle it carefully as it may contain sensitive information. It is also essential to ensure that the state does not conflict, especially on large teams, by using locks.

By default, the state is stored in the “local” backend: a file is generated in the path where our configuration files are located. However, in team environments or to ensure better security and versioning, it is advisable to use remote backends such as Azure Blob Storage, AWS S3, among others.

Remote State

Remote State is the recommended solution for collaborative work with Terraform. It will allow several people/teams to work on the same infrastructure. Using a fully functional state backend, Terraform can use Remote State Lock as a measure to prevent two or more users from running Terraform simultaneously, ensuring that each run starts with the most recently updated state.

By using Google Cloud Bucket Storage or GCS (or any remote storage solution), you ensure that your Terraform state is centralized, encrypted, versioned, and accessible to those who need it, which is essential for proper infrastructure management with Terraform, especially in team and production environments.

Now, let’s see how to configure it in a GCP project. For this we are going to have to review some important points:

Authentication

In the first instance we are going to have to create a Service Principal in GCP that allows us to authenticate and authorize our access to GCP securely.

What is a Service Account in GCP?

A Service Account (SA) in GCP is a type of IAM Identity that will allow us to use GCP APIs or resources securely. They are used instead of normal users to access services such as VM instances, Applications or in this case a Google Cloud Storage (GCS) to use Terraform. This means that it is ideal for “Server-to-Server” interactions, avoiding user interaction.

It is important to implement Least Privilaged Access for our SAs so that they fulfill a unique function. In this case we will use it to log in with Terraform: that is, this service account should only have permissions to create, modify or delete resources in our GPC Scope (in our case the selected project)

How is authentication done using Service Accounts in GCP?

Service Accounts use Key pairs to log in to our resources. This Key is stored, used by GCP and its life cycle can be managed using both the console and the command line.

Service Account Creation

Now let’s create our Service Account:

  • First of all, we will enter our GCP Console.
  • We will enter the “IAM & Admin” section and select “Service Accounts”.
  • Then we will click on “+ Create Service Account”.
  • Once in the wizard we will complete the Service Account Data.
  • Then we will give you the necessary permissions. In this case, for demo purposes, we will give you editor permissions. But we must always try to keep Least Privilege in production.
  • Then we will click on “Done”.
  • We can see that our Service Account was created.
  • Now we will generate our Key. For this we must click on the created SA.
  • Then we must select the “Keys” tab. Then, click on “Add Key”.
  • We will select the JSON format and click on “Create”.
  • The creation will end:
  • And the Key will be saved on our computer.
  • As we can see in the downloads section of our browser.
  • In this case we will send the file to the repo of our Terraform code (safer alternatives can be sought in production) and we will exclude the file to be managed by Git through .gitignore.
  • We can see the content of the Key.

Creating the Cloud Storage Bucket

Now we must create our Cloud Storage Bucket in Google Cloud Storage (GCS). For this we can follow the following tutorial:

https://cloud.google.com/storage/docs/creating-buckets?hl=es-419

In this case, the created bucket is called mc-state:

Set up authentication for Terraform

Now we need to configure authentication for Terraform.

For practical purposes of the demo, we will configure the environment variable in PowerShell, but we can also do it through the environment variables of our Git repository (this is the most recommended).

We will execute the following command:

PowerShell
$env:GOOGLE_APPLICATION_CREDENTIALS="heroic-dynamo-410801-ba0880d89d64.json

Backend.tf Configuration

Now we will configure our Backend code. In this case, I will be generating a file for this purpose called “backend.tf” in the root directory:

HCL
terraform {
required_providers {
google = {
source = "hashicorp/google"
version = "3.5.0"
}
}
backend "gcs" {
bucket = "mc-tfstate"
prefix = "terraform/state"
}
}
Spanish counterpart reference: Terraform backend configuration
Archived Spanish counterpart: Terraform backend configuration
Reference from the Spanish counterpart; the original English capture was unavailable.
  • In this file, we will configure the required provider for our backend.
  • And also, we will configure the Backend itself: we will specify the name “gcs” and we will set the bucket name and the file prefix.

It is important to mention that the file prefix only involves the file directories and not the name itself. The file name will correspond to the Workspace that Terraform is in. In general, if it has not been changed on our command line this will be the Default. For this reason, the file name will be “default.tfstate”.

Start Terraform configuration

We will start the Terraform configuration using the following command

Bash
terraform init
Bash
Initializing the backend...
Initializing modules...
Initializing provider plugins...
- Reusing previous version of hashicorp/google from the dependency lock file
- Using previously-installed hashicorp/google v3.5.0
Terraform has been successfully initialized!
You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.
If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

Historical output. The prompt and already-copyable command are omitted to avoid duplicating them.

Spanish counterpart reference: terraform init output
Archived Spanish counterpart: terraform init output
Reference from the Spanish counterpart; the original English capture was unavailable.

Once started, we can verify that the State was created as mentioned in the previous point:

Archived Spanish counterpart: Terraform state in the Google Cloud console
Reference from the Spanish counterpart; the original English capture was unavailable.

Mateo Di Loreto

Thanks for reading. The learning continues in the next article.