Create resource based on presence of file

What’s the correct way to always create a resource if a file does not exist
My attempt

resource "null_resource" "this" {
  count = fileexists(pathexpand("~/somefile.sh")) ? 0 : 1   # always create resource if file does not exist

  provisioner "local-exec" {
    command = <<EOF
      echo "Creating ~/somefile.sh"
    EOF
  }
}

Use the local file resource?

https://registry.terraform.io/providers/hashicorp/local/latest/docs/resources/file

@stuart-c Just to clarify on my requirement. What I want to do in local-exec is download some files and run a bunch of commands. So in this case it’s not just one file I want created.

I want null_resource to run always if a given file doesn’t exist.

The only solution I could think of is always create the file. But it means Terraform resource is not very idempotent if the file already exists.

resource "null_resource" "this" {
  triggers = {
    timestamp = timestamp()
  }

  provisioner "local-exec" {
    command = <<EOF
      echo "Creating ~/somefile.sh"
    EOF
  }
}

Hi @deasunk,

Unfortunately what you are doing here (using Terraform to manage local files outside of the current working directory) is pretty unusual and not really in Terraform’s intended scope, so there aren’t really good facilities for doing it built into the Terraform language.

I expect there are ways to make it work, since ultimately a Terraform configuration is arbitrary code that can (with the help of providers) be convinced to do just about anything that a computer can typically do, but I don’t have a direct answer to your question ready to go.

Instead, I might suggest looking for a different approach where your Terraform configuration can avoid modifying the local filesystem outside of its scope. I don’t really know what to suggest since I don’t have any information on the real underlying use-case behind this solution you’ve tried, but I’d be happy to try to make some suggestions if you’d be willing to share some more details about what your underlying goal is, independent of any particular Terraform-based solution to that goal.