Can I use variables in the TerraForm main.tf file?

Viewed 7782

Ok, so I have three .tf-files: main.tf where I state azure as provider, resources.tf where all the my resources are claimed, and variables.tf.

I use variables.tf to store keys used by resources.tf.

However, I want to use variables stored in my variable file to fill in the fields in the backend scope like this:

main.tf:

provider "azurerm" {
    version = "=1.5.0"
}

    terraform {
        backend "azurerm" {

        storage_account_name = "${var.sa_name}"
        container_name = "${var.c_name}"
        key = "${var.key}"
        access_key = "${var.access_key}"
    }
}

Variables stored in variables.tf like this:

variable "sa_name" {
    default = "myStorageAccount"
}

variable "c_name" {
    default = "tfstate"
}

variable "key" {
    default = "codelab.microsoft.tfstate"
}

variable "access_key" {
    default = "weoghwoep489ug40gu ... "
}

I got this when running terraform init:

terraform.backend: configuration cannot contain interpolations

The backend configuration is loaded by Terraform extremely early, before the core of Terraform can be initialized. This is necessary because the backend dictates the behavior of that core. The core is what handles interpolation processing. Because of this, interpolations cannot be used in backend configuration.

If you'd like to parameterize backend configuration, we recommend using partial configuration with the "-backend-config" flag to "terraform init".

Is there a way of solving this? I really want all my keys/secrets in the same file... and not one key in the main which I preferably want to push to git.

2 Answers

Terraform doesn't care much about filenames: it just loads all .tf files in the current directory and processes them. Names like main.tf, variables.tf, and outputs.tf are useful conventions to make it easier for developers to navigate the code, but they won't have much impact on Terraform's behavior.

The reason you're seeing the error is that you're trying to use variables in a backend configuration. Unfortunately, Terraform does not allow any interpolation (any ${...}) in backends. Quoting from the documentation:

Only one backend may be specified and the configuration may not contain interpolations. Terraform will validate this.

So, you have to either hard-code all the values in your backend, or provide a partial configuration and fill in the rest of the configuration via CLI params using an outside tool (e.g., Terragrunt).

There are some important limitations on backend configuration:

  1. A configuration can only provide one backend block.
  2. A backend block cannot refer to named values (like input variables, locals, or data source attributes).

Terraform backends configurations one can see at below link: https://www.terraform.io/docs/configuration/backend.html

Related