Terraform append to list

Hi, I have a question. I have a list, which contains [“a”,“b”]. I am not storing this value anywhere, I am passing this value at runtime. So my question is, is there a way that I can keep on appending to the list? I am using a local_file resource with a template file. Is there a way that I can achieve this using the tfstate file and using the merge function?

My idea is I am running this command
terraform plan --var=zones=[“a”,“b”]
without any state file and I am generating a file with the following contents

  • a
    So next. time when I run the command terraform plan --var=zones=[“c”],
    Can I get the value appended something like
  • a
  • b
  • c

Hi @infa-pavakuma,

This is not how Terraform works; your configuration must always be a full description of the entire set of objects you want Terraform to manage, and so if you wish to retain existing objects on a future run you must keep all of those objects declared and only add new objects. This is true regardless of whether you are writing the resource blocks out manually or if you are driving a set of resource instances from an input variable.

You will therefore need to build something outside of Terraform that can somehow remember that “a” and “b” should exist and then generate the whole set “a”, “b”, “c”. On your next run.

One way to achieve this is to store this set of strings in an external configuration store, such as AWS SSM Parameter Store if you are using AWS, and then use a data source to retrieve that data from the external store, instead of an input variable. The workflow would then be to modify the configuration store outside of Terraform whenever you want to add another zone and then run Terraform without any extra arguments to make Terraform notice that the configuration store has changed and plan infrastructure changes in response to that.

Another simpler option is to put your list of zones in your version control system as part of your Terraform configuration and then edit that configuration file each time you need to add or remove a zone. In that case, your version control system is the “memory” for what should currently exist, so you don’t need any external data store.