1
votes

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!

2
That’s not really how Terraform works. You are declaring what you want a resource to look like. Change the declaration, the resource follows suit. Change nothing and the resource stays the same, no matter how many times you apply the config.Scott Heath

2 Answers

1
votes

This document says nothing about maintaining state which is what you need but it does have useful info on variables - https://medium.com/@milescollier/handling-environmental-variables-in-terraform-workspaces-27d0278423df

you can also do -

variable "template" {
    type = "string"
    default = "01000000-0000-4000-8000-000030080200"
}

or 

variable "environment-type" {
  type = "map"

  default = {
    dev = "DEVELOPMENT"
    preprod = "PRE-PRODUCTION"
    prod = "PRODUCTION"
  }
}
1
votes

I was trying to do something similar and came across this post. Worked out a solution in the end so thought I should share for anyone else coming across this post.

variable "maintenance" {
  description = "Set to active, disabled or previous (Default)"
  type        = string
  default     = "previous"
}

# This is used so we can lookup the previous value of the maintenance setting in the state file
data "terraform_remote_state" "bc" {
  backend = "gcs"

  config = {
    bucket = "terraform-bucket"
    prefix = "terraform/state"
  }

  workspace = terraform.workspace

  # Set a default value in case of an empty state file
  defaults = {
    maintenance = "disabled"
  }
}

locals {
  maintenance_status = var.maintenance == "previous" ? data.terraform_remote_state.bc.outputs.maintenance : var.maintenance
}

# Used to expose the current value to subsequent tf runs
output "maintenance" {
  value = example_resource.maintenance.status
}

You can then change the setting using the command line, but if not specified it will use the previous value terraform apply -var="maintenance=active"