15

I am wondering if it is possible to retrieve the fields explicitly provided to the backend config elsewhere in the module.

There are many people on the internet asking if it's possible to use variables to set up the backend. I know that is impossible because of the order of operations performed by terraform -- but I want to do the opposite.

An easy to explain example would be if I wanted to pass the backend state bucket/key to a tag on a resource. I could write the state key twice (once in the backend config and once as a variable) but that violates DRY and could be error-prone or at best annoying.

I understand why it is not possible to have variables in the backend config, but I can't imagine any technical constraint to prevent the backend config from being referenced elsewhere in the module. Still I have not been able to find any way to do it, and attempts to google it are flooded by people looking to put variables in the backend config. Perhaps there is an easy syntax I've not been able to find, or perhaps it is not supported and I could consider a feature request.

So is there currently a way to do this?

0

2 Answers 2

13

How about passing backend config file as tfvars file to terraform apply or terraform plan? then you can reference it as variables. You can pass multiple tfvars files to terraform with -var-file parameters.

for example backend-config.tfvars

bucket = "test-bucket"
key = "test/terraform.tfstate"
...

and variables.tf

...
variable "bucket" {
 description="backend bucket"
}
variable "key" {
 description="backend key"
}

then you can init terraform,

terraform init -backend-config=backend-config.tfvars

and

terraform plan -var-file={your varfile} -var-file=backend-config.tfvars
3
  • 1
    +1 although I am looking specifically for if a syntax does or could exist to reference the backend simply and directly, this is an interesting workaround! I did not know that backends could be configured this way. Commented Jul 10, 2019 at 16:26
  • you can also expose the values in a .backend file similar to a .env file described in this SO: stackoverflow.com/a/72888812/2127315
    – cedric
    Commented Feb 2, 2023 at 13:45
  • 2
    The problem with this is you can potentially mix up backends and end up overwriting the state belonging to a different application. I wish I could use the backend variables once I create them with init
    – gk_2000
    Commented Sep 9, 2023 at 6:09
0

Do you know the remote state Provider? You can read it back in as a data resource. This is what the terraform doc says.

1
  • 1
    Thanks, but the remote state provider is used from stack B to get remote state (stored on the Backend) about stack A. What I am asking about is getting Stack A's backend configuration from within stack A, but outside the backend config block. Commented Jul 16, 2019 at 22:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.