Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can terraform backend fields be accessed as variables?

Tags:

terraform

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?

like image 975
user1169420 Avatar asked Jul 10 '19 00:07

user1169420


1 Answers

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
like image 199
RyanKim Avatar answered Oct 20 '22 15:10

RyanKim