Can I find the name of the tfvars file used on the terraform apply command

Is there a way within a module to find the name of the tfvars file used when terraform apply was run? I frequently run the terraform apply --var-file="xxxx.tfvars" and would like to be able to find the name of that file from within my modules. Thanks!

I don’t think you can. I am curious about the use case tho. Would you mind to share?
There might be something you could do with a different approach.

The use case is that as part of the terraform provisioning of a VM, we want to have ansible do additional configuration after the VM has been provisioned. The terraform module runs a shell script that reads the tfvars as input and reformats it into something that ansible can consume. If I don’t know the name of the file, I need to hardcode it. We typically use these terraform scripts to build test clusters. By convention, if I want to build “ClusterA”, I will build files clustera.tfvars and clustera.tfstate when I run the terraform (eg terraform apply --var-file=“clustera.tfvars” --state=“clustera.tfstate”) This allows me to have multiple clusters in various states. I suppose I could just switch to a directory structure that supports this, thus keeping the tfvars file the same, but it would probably require some retesting and retooling. (which I will probably need to do anyway)

Maybe I will just go with the Terraform templatefile route, the person who wrote the shell script was an Ansible person not a Terraform person and I should be able to convert it over fairly quickly.

Remember also that it isn’t necessarily a single tfvars file. You can specify multiple on the command line but Terraform will also automatically pickup the terraform.tfvars and *.auto.tfvars files in the current directory too. The ordering also matters in the case a several files trying to set the same variable.

Overall I’d suggest generating the file using templatefile as otherwise it sounds like you are trying to tie things into a Terraform implementation detail too tightly, which might cause future issues (what if you have defaults for a variable so don’t have it in the tfvar file, what if you split things into multiple files, etc.)

Are you deploying on a public cloud or kube?

I found that using remote states or .tfvars was not necessarily a smart thing to interoperate with other tools like Ansible. I have always had a better and simple approach to use some K=>V store in the cloud provider. Example SSM for AWS.

But as you said, if this is a transitional state and can wait to be reimplemented fully with TF, you are better placed to see if that’s worth it (annoyance/benefit).

I switched the terraform to populate a template to create the ansible yaml. This will use the correct values regardless of where they came from.

so you’re retooling fast, nice :wink: using a provisionner I guess?