Creating a resource that only keeps a data type in the state but does nothing else

Is there a resource type that lets me store an arbitrary string (or perhaps any data type) in the terraform state, but does not represent that state in any other way? This is a lot like local_file but without actually creating a file locally.

I’d like to maintain state between certain values and show a diff when they change, but how they end up represented in the infrastructure can be rather involved.

It sounds like null_resource may be suitable.

null_resource doesn’t have any outputs that let me store a value in TF state. However, it’s almost what I want because it has trigger state which is kept. If I could get that trigger state and see a diff between the previous state and the new state on terraform apply, that would be very close indeed.

If you want an output variable based on the null_resource’s triggers, you can simply define that:

output "foobar" {
  value = null_resource.foobar.triggers
}

Ah great to know. Sadly, by definition I always know the current value of the trigger. I guess what I’m really after is the diff between the previous trigger state and the new one.

Oh my. null_resource already does that! This might be exactly what I need! Thank you!

As a general rule, the Terraform configuration only describes the desired state and cannot refer to the prior state. It’s the responsibility of a provider to notice differences between prior state and desired state, and propose actions to reconcile them.

null_resource does offer a limited way to indirectly access the prior state in that it will propose a “replace” action for itself whenever it detects a difference in triggers, but it isn’t a general mechanism for making the desired state vary based on the prior state.

It is possible in principle for a provider to offer a resource type that behaves in this way – exporting a copy of the values written last time separately from the values currently configured – but I think it would be hard/impossible to implement that in a way that allows updating the values after initial creation, because Terraform Core will raise an error if a provider tries to produce a final state that doesn’t match the plan, and so it wouldn’t be possible for the provider to offer the old values during the planning phase but then the updated values during the apply step.

(I can think of some ways that might work by subverting the intent of the different phases of the resource instance change lifecycle, but my sense is that if you need to do this then your use-case is probably not within Terraform’s intended scope and so it may be better to select a different tool.)