Iterate over diff of variable

I’d like to perform an action based on the values additionally added to a list variable. So given a list of [1,2], when 3 is added, take action of 3. But I’d like to ignore changes when values are removed.

Is this possible?

Hi @mhumeSF,

There is no generalized mechanism to do what you described here.

However, if you can share more details about the higher-level problem you are trying to solve, I or someone else might be able to suggest a different strategy that fits within the Terraform model.

I think I found a solution, but essentially generating a list of users to iterate an action on as they are added to a list, but not when they are removed. This relies on the terraform state to be present first. Here’s what I’ve done roughly.

locals {
  users = {
    "tom" = ["null"],
    "dick" = ["null"],
    "harry" = ["null"],
    "alice" = ["null"],
  }
}

data "terraform_remote_state" "local" {
  backend = "local"
  config = {
    path = "terraform.tfstate"
  }
}

output "users" {
  value = keys(local.users)
}

output "data" {
  value = data.terraform_remote_state.local.outputs.users
}

output "delta" {
  value = [ for user in keys(local.users): user if !contains(data.terraform_remote_state.local.outputs.users, user) ]
}

I have never seen anybody using a recursive state before :exploding_head:

“Douze points” for thinking outside the box :star_struck:

That is a creative approach indeed!

I would caution that Terraform is not designed to be expecting to consume its own output as a data source, and so what you’re doing there is not guaranteed to keep working exactly the same way in future releases: you’re relying on an implementation detail of how Terraform interacts with the local backend.

Off the top of my head I can’t think of anything actually planned that would break it, but I’d strongly suggest putting a comment on that to give a potential future maintainer a hint if they upgrade to a new major version of Terraform someday and start seeing some odd behavior. Also would suggest including an explicit Terraform version pin in your configuration to reduce the risk of inadvertently adopting a new version with different behavior.