How to implement “sticky” variables in terraform?

I’d like to have a Terraform variable with these properties:

  • if it has never been set, use a default value
  • if no value is provided, use the value from the previous run
  • if a value is provided, use that and remember it

The use case is for AWS ECS tags, where I want to be able to deploy a new version by changing the tag, which will cause Terraform to create a new task definition and modify the service definition. If I run “terraform apply”, though, without passing a new value I’d like nothing to happen, i.e., terraform remembers the value from the previous run.

Suggestions welcome!

Hi @caboteria,

This sort of workflow unfortunately isn’t really supported by Terraform’s model. The usual way to represent something like this is for the configuration itself (in version control) to act as the “memory”.

In other words, you make changes to infrastructure by making changes to the configuration via pull request, and if you don’t change anything then terraform apply is a no-op, preserving everything from the previous run.

You can get a little closer to what you want by introducing some sort of external configuration source. If changing the configuration in order to deploy a new version isn’t desirable, you can add some indirection by making Terraform refer to some other system using a data block, and then have your release process include making a change to that other system.

As a concrete example, if you are using AWS you could create an AWS SSM Parameter that represents the current version, and use aws_ssm_parameter to retrieve it’s value to use elsewhere in your Terraform configuration. Then when you wish to select a new version, you can have your release process write a new value into that parameter and then begin a Terraform run to apply that change without modifying the configuration.

1 Like

Thanks for the insight @apparentlymart, I especially appreciate the detailed explanation! Your workaround looks interesting. Since I’m deploying to AWS it’s reasonable to store the version data there, too.