= 0.13" required_providers { google = { source = "hashicorp/google version = "~> 4.9.0" } } backend = "gcs" { bucket " /> = 0.13" required_providers { google = { source = "hashicorp/google version = "~> 4.9.0" } } backend = "gcs" { bucket " /> = 0.13" required_providers { google = { source = "hashicorp/google version = "~> 4.9.0" } } backend = "gcs" { bucket "/>

Parametrizing backend in terraform on gcp

26 Views Asked by At
terraform {
    required_version = ">= 0.13"
    required_providers {
          google = {
           source = "hashicorp/google
           version = "~> 4.9.0"
        }
    }
   backend = "gcs" {
        bucket = "my-bucket"
        prefix = "/tfstate/{_NONLIVE_OR_LIVE}/{country}"
   }
}

I try to parametrize "terraform init" so that I can use the same main.tf file for six different use cases (_PREPROD_OR_PROD can be either pre-prod or prod; country can be either Portugal, Italy or Spain).

In the cloudbuild.yaml file I have to the same terraform_apply.yaml file for all six usecases and I want to specify it like "terraform init -backend-config="PREPROD_OR_PROD=${_PREPROD_OR_PROD}" -backend-config="{COUNTRY=${_COUNTRY}"

How can I implement this in terraform and Google Cloud/ GCP?

1

There are 1 best solutions below

0
Rui Jarimba On

You're probably not using the -backend-config properly, see Partial configuration for more details.

You should use with with this format:

terraform init -backend-config="KEY=VALUE"

Where:

  • KEY is the configuration option to set (like prefix or bucket)
  • VALUE is the value to set it to (like /tfstate/{_NONLIVE_OR_LIVE}/{country}).

Consider the following backend:

terraform {
  backend "local" {
    path = "foobar.tfstate"
  }
}

I can change the path using the following command:

terraform init -backend-config="path=./dev.tfstate"

ENVIRONMENT="prod"
terraform init -backend-config="path=./$ENVIRONMENT.tfstate"

This will generate a prod.tfstate in the local folder.

Now, back to your code:

terraform {
  backend "gcs" {
    bucket = "foo"
    prefix = "bar"
  }
}

I haven't tested this but I suppose you can do something like:

BUCKET="my-bucket"
ENVIRONMENT="pre-prod"
COUNTRY="Portugal"

terraform init \
  -backend-config="bucket=$BUCKET" \
  -backend-config="prefix=/tfstate/$ENVIRONMENT/$COUNTRY"

As an alternative, you can use terragrunt to automatically generate the remote backend for each environment.