Reputation: 716
I am using Terraform to execute a script to apply some configuration that are not handled via a provider.
This is done using a null_resource.
The executed script will generate a configuration with a name based on current values. Terraform does not keep track of anything created within a null_resource.
The created configuration should also be updatable. But in order to do that I need to know the values used in the prior execution.
Then the old configuration can be targeted by its name, deleted and the new configuration can be added.
So two consecutive runs would look like this:
I imagine something like this:
resource "null_resource" "start_script" {
# Not actual code! I would like to access the old value with var.name.old
# but I don't know how.
provisioner "local-exec" {
command = "../scripts/dosth.sh ${resource.name.value} ${resource.name.value.old} ${var.name} ${var.name.old}"
interpreter = ["/bin/bash", "-c"]
}
}
Is there a way to access the "old" value of a resource/variable in general, or from the context of a null_resource in particular?
What I know I could already do when adding workarounds:
terraform state show name -raw
to extract the value from the state and use it as an input in the new run.Upvotes: 2
Views: 2289
Reputation: 74594
Within the Terraform language itself (.tf
files) we only work with the desired new state, and don't have any access to the prior state. Terraform evaluates the configuration first and then, with the help of the associated provider, compares the result of evaluating the configuration to the prior state in order to determine what needs to change.
If you want to respond to changes between the prior state and the desired new state then your logic will need to live inside a provider, rather than inside a module. A provider is the component that handles the transition from one state to another, and so only a provider can "see" both the prior state and the desired state represented by the configuration at the same time, during the planning phase.
The community provider scottwinkler/shell
seems to have a resource type shell_script
which can act as an adapter to forward the provider requests from Terraform Core to some externally-defined shell scripts. It seems that if you implement an update script then it can in principle access both the prior state and the new desired state, although I'm not personally familiar with the details because I've not actually used this provider. I suggest reviewing the documentation and the code to understand more about how it works, if you choose to use it.
Upvotes: 4