How do I pass the Terraform storage account for the backend as variable?
I get the following error:
#main.tf
terraform {
required_version = ">= 1.3"
backend "azurerm" {
resource_group_name = "rg-tfstate"
storage_account_name = var.arg5_terraformStorageAccount
container_name = "tfstate"
key = "terraform.tfstate"
}
#variables.tf
variable "arg5_terraformStorageAccount" {
type = string
description = "terraformStorageAccount (sensitive)"
sensitive = true
}
│ Error: Variables not allowed
│
│ on main.tf line 7, in terraform:
│ 7: storage_account_name = var.arg5_terraformStorageAccount
│
│ Variables may not be used here.
2
Answers
I ended up using substitution.
So I renamed my main.tf file to main.tftemplate
In there I named the variable that I wanted to define dynamically
STORAGEACCOUNT
In my Github Actions I specified a variable called
AZURE_TF_STORAGE_ACCOUNT
Then before I run Terraform Apply, I run the following
sed "s/STORAGEACCOUNT/${{ vars.AZURE_TF_STORAGE_ACCOUNT }}/g" main.tftemplate > main.tf
This replaces
STORAGEACCOUNT
in main.tftemplate with the variable I added to Github Actions and it writes it into the main.tf file.You can do that with any String inside a file.
You can’t do this, as you can’t use any variables in
backend
. You have to hardcode the value, or develop some-kind of wrapper around TF to do simple find-and-search substitution.