Reputation: 1200
We're in the middle of working on a small proof of concept project which will deploy infrastructure to Azure using Terraform. Our Terraform source is held in GitHub and we've using Terraform cloud as the backend to store our state, secrets etc.
Within Terraform cloud we've created two workspaces, one for the staging
environment and one for the production
environment.
So far we've used the guide on the Terraform docs to develop a GitHub action which triggers on a push to the main
branch and deploys our infrastructure to the staging
environment. This all works great and we can see our state held in Terraform cloud.
The next hurdle is to promote our changes into the production
environment.
Unfortunately we've hit a brick wall trying to figure out how to dynamically change the Terraform cloud workspace within the GitHub action so it's operating on production
and not staging
. I've spent most of the day looking into this with little joy.
For reference the Terraform backend is currently configured as follows:
terraform {
backend "remote" {
organization = "terraform-organisation-name"
workspaces {
name = "staging-workspace-name"
}
}
}
The action itself does an init
and then and apply
.
Obviously with the workspace name hardcoded this will only work on staging
. Ultimately the questions comes down to how to parameterise or dynamically change the Terraform cloud workspace from the command line?
I feel I'm missing something fundamental and any help or suggestions would be greatly appreciated.
Upvotes: 2
Views: 752
Reputation: 7066
You need to do something like this.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
}
}
cloud {
hostname = "app.terraform.io"
organization = "Your-Org"
workspaces {
tags = [
"my-service",
"infrastructure",
]
}
}
}
Then you create a workspace for each environment which has ALL of the tags you have specified in the tags
block. You can then use the TF_WORKSPACE
environment variable to point at the correct workspace.
$env:TF_WORKSPACE="staging-workspace-name"
terraform plan
Upvotes: 0
Reputation: 1005
You should be able to run terraform workspace select production
in the same way you would do locally.
If, for some reason, you absolutely need to use this config file, then you could just generate it before you run terraform apply
. For example, run something like sed -i 's/staging/production/g' backend.tf
to perform the replacement.
Upvotes: 0