Trigger a data source based on a condition

Hi folks,

I am unable to trigger a data source on demand. My goal is to trigger it only when a null_resource is triggered due to a change in the executable version. If there is a new executable version, both the null resource and the data source should be executed. Otherwise, neither of them should be executed.

The code is as below:
Null resource that executes a script

resource "null_resource" "model-deploy" {
  provisioner "local-exec" {
    command = "${path.cwd}/scripts/ -c '${var.credentials}' -e '${var.executable_id}' -s '${var.scenario_id}' -v '${var.executable_version}' -o '${path.cwd}/my_ips.txt' -k '${var.skip_model_deployment}' -t '3600' -r '${var.resource_plan}'"
  triggers = {
    aicore_model_update = "${var.executable_version}"

A data source that reads a file content generated in by the null resource

data "local_file" "my-ip" {
  filename   = "${path.cwd}/my_ips.txt"
  depends_on = [null_resource.model-deploy]

How can I achieve this?

Thanks a lot in advance :slight_smile:

Hi @fadhel.salhi,

It will not be possible to achieve exactly what you described. Terraform’s declarative model does not allow describing situations like “read this only if some other thing was just created”.

In general also Terraform modules should ideally not modify their own directory contents while they are running, since that tends to lead to a brittle configuration that might e.g. behave strangely if applied in a directory which still contains files generated on a previous run.

If there is no Terraform provider available that directly supports whatever your is doing, and so there’s no alternative to running an external program here, a potential compromise is to use one of the community providers available in the Terraform Registry that allows using an external program as the implementation of a managed resource (a resource block).

I can’t recommend any specific provider because I don’t have a lot of “real-world” experience with them, but here is one example I found with the registry search just as an example of what I mean:

According to the documentation, the resource type in that provider exports a map of strings containing the output of the script from each phase, and so if you change your script to print its result to its stdout, instead of writing to a separate file, then you will already have that result in memory in Terraform and so will not need to read it from disk at all.

1 Like