Can I destroy cloud infrastructure using `.tfstate` file of a sepecific project?

51 views Asked by At

I have multiple projects on Hetzner Cloud (testing, production). I use the same code to create the services in these projects. Consider I want to create a load balancer in testing project, I will get a .tfplan file. But the problem is that if I do the same for the production project my code will just replace the previous .tfplan file.

Now I can create multiple plan files and save them in the respective directories, but I don't want that and I can only create multiple .tfstate for each project. So my question, is there any way to destroy the infrastructure using the state files.

I have followed these steps but no success so far.

  1. Get the state file for loadbalancer (lb.tfstate).
  2. Run terraform plan -destroy -state=lb.tfstate -out lb.tfplan.
  3. Run terraform apply -destroy lb.tfplan.
1

There are 1 answers

0
fmueller On

You can use providers for your terraform states, like s3: https://medium.com/all-things-devops/how-to-store-terraform-state-on-s3-be9cd0070590

Setting custom names / locations for .tfstate files is a bit weird. I've been using terraform since wham and never seen anyone do this.

Commonly you have one terraform directory per project, something like:

~/code/customer/project/production/main.tf
~/code/customer/project/staging/main.tf
~/code/customer/project/tools/main.tf

and so on. terraform will automatically create state files in these directories.

Ideally you want ~/code/customer/project (or alike) to be a git repository.

If you want to use the same main.tf file in stag and prod I'd just use a symlink:

ln -s ~/code/customer/project/production/main.tf ~/code/customer/project/staging/main.tf

But messing with the state files is a big no-no. I'd recommend not to do that.