TS_ENV custom variable on backend

Hi…

if possible use variables on backend ?

if i use

vim boot/dev.rb

ENV['TS_ENV_SHORT'] ||= 'prod'
TS_ENV='dev'

and after in backend

This works
bucket = "<%= expansion('terraform-state-:ACCOUNT-:REGION-:ENV') %>"

This not works :frowning:
bucket = "<%= expansion('terraform-state-:ACCOUNT-:REGION-:TS_ENV_SHORT'') %>"

error output

NoMethodError: undefined method `ts_env_short' for #<TerraspacePluginAws::Interfaces::Expander:0x0000000002e59d20>
Error evaluating ERB template around line 3
 1 terraform {
 2   backend "s3" {
 3     bucket         = "<%= expansion('tfstate-:ACCOUNT-:MOD_NAME-:REGION-:TS_ENV_SHORT') %>"
 4     dynamodb_table = "<%= expansion('tfstate-:ACCOUNT-:MOD_NAME-:REGION-:TS_ENV_SHORT') %>"
 5     key            = "<%= expansion(':BUILD_DIR/:REGION/:TS_ENV_SHORT/terraform.tfstate') %>"
 6     region         = "<%= expansion(':REGION') %>"

any idea?

we are using

CentOS 8
terraspace 0.6.23
terraform 1.0.6

TLDR

Use this:

bucket = "<%= expansion("terraform-state-:ACCOUNT-:REGION-#{ENV['TS_ENV_SHORT']}") %>"

It’s using string interpolation to get the value from the ENV before passing it to the expansion method.

Details

The expansion method grabs “variables” from the string by looking for the : symbol. These “variables” are used as the actually method to call on cloud-specific expander classes. IE:

:ENV => env method 
:REGION => region method 
:BUILD_DIR => build_dir method 

The methods are implemented in Expander classes and provided by each cloud specific plugin. Examples:

This because different clouds require different logic to look up the value. IE: The region method is different for AWS vs Google Cloud. These expander methods usually do not simply return the env var value.

Am wondering though, if should also add some fallback logic to try and grab the env var if it set when methods are not explicitly defined in the cloud plugin expander interface classes. Maybe use method_missing as a fallback and check if the env var is set. Unsure though. Will have to let it simmer on the brain.

1 Like

Thanks this works…