Tfvars: Dynamic

The tfvars files get processed by ERB templating, providing some dynamic control.

Example 1: output

A useful helper is output, it allows you to grab the output value from another stack and use it as an input variable for another stack.

config/stacks/demo/tfvars/base.tfvars:

vpc_id = <%= output("vpc.vpc_id")" %>

Terraspace also uses this information to build the dependency graph and deploys the dependent stacks in the correct order with terraspace all up. Related useful docs:

Example 2: General

One example is maybe you want to use TS_ENV in your variables dynamically with the ERB.

config/stacks/demo/tfvars/base.tfvars:

name = "<%= Terraspace.env %>-instance"

Then:

TS_ENV=dev terraspace build demo

Results in:

name = "dev-instance"

And:

TS_ENV=prod terraspace build demo

Results in:

name = "prod-instance"

Example 3: TS_EXTRA Example

Here’s an example with the TS_EXTRA env var in a tfvars file.

config/stacks/server/tfvars/base.tfvars:

name = "<%= Terraspace.extra %>-server"

So:

TS_EXTRA=bob terraspace up server

Results in:

name = "bob-server"

So:

TS_EXTRA=kevin terraspace up server

Results in:

name = "kevin-server"

Recommendation

Using ERB in the tfvar files is a pretty clean way of adding a little bit of dynamism. A good thing about the approach is that it keeps your Terraform module code purely native. When possible, it is recommended to use the ERB power that terraspace provides responsibly though.

More tools: