This blog post will demonstrate how to set up Terraform remote state and storage on GCP using a step-by-step guide.
Terraform’s remote state allows us to retain and maintain the state of our infrastructure from multiple devices and services and even collaborate with team members.
When working with GCP, we can maintain the state of our infrastructure deployment in a GCP bucket and use it with Azure Pipelines when deploying infrastructure to GCP.
Remote State
To get started with our GCP terraform remote state, we need to ensure its prerequisites are met. Before you start, make sure you have the following.
- Download and install the Google Cloud CLI for your operating system.
- Terraform is installed on your machine.
Google Cloud CLI Setup
Create a Storage Bucket for Remote State
terraform {
required_providers {
google = {
source = "hashicorp/google"
version = "5.23.0"
}
}
}
provider "google" {
project = "terraform-419023"
region = "australia-southeast2"
credentials = file("creds.json")
}
resource "random_id" "bucket_prefix" {
byte_length = 8
}
resource "google_storage_bucket" "default" {
name = "${random_id.bucket_prefix.hex}-bucket-tfstate"
force_destroy = false
location = "australia-southeast2"
storage_class = "STANDARD"
versioning {
enabled = true
}
}
Before deploying the storage bucket, run the following gcloud command to authenticate to GCP.
gcloud auth login
After authenticating successfully, run the following commands.
terraform init
terraform plan
terraform apply
Use Remote State
To use the GCP remote state in another terraform configuration. Add the following code to your config.
terraform {
backend "gcs" {
bucket = "972e5b5168349ea6-bucket-tfstate"
prefix = "terraform/state"
credentials = "creds.json"
}
}
A full configuration file that uses a GCP remote state looks like this.
terraform {
required_providers {
google = {
source = "hashicorp/google"
version = "5.23.0"
}
}
}
terraform {
backend "gcs" {
bucket = "972e5b5168349ea6-bucket-tfstate"
prefix = "terraform/state"
credentials = "creds.json"
}
}
provider "google" {
project = "terraform-419023"
region = "australia-southeast2"
credentials = file("creds.json")
}
resource "google_storage_bucket" "storage_account" {
name = "my-storage-account2"
location = "australia-southeast2"
}
To change your terraform remote state from local to GCP, run
terraform init
Related Articles
- Store Terraform State Files in Azure Remote Backend
- Enable Terraform Remote Backend on AWS S3
- Configure Docker Container Replicas With Docker Compose
- Deploy GCP Infrastructure Using Terraform and Azure DevOps
- Connect To Exchange Servers Using Remote PowerShell Exchange Server