Someone changed your terraform!

Juan Matías de la Cámara Beovide
tarmac
Published in
2 min readNov 10, 2020

What?

So, someone deployed to production using a terraform file set. Then someone else modified something there and after a looooooong time, it’s your turn to fix some stuff.

Specifically what?

Ok, for this example, at first moment you had a Google Service (here we are working with Cloud Functions), activated in the main file of this terraform structure:

. 
├── env
│ └── main.tf
└── function
├── http_trigger.js
└── http_trigger.zip

This means, the service address was: google_project_service.cloud-functions

Then someone had the great idea: using modules! :)

So the Google Service activation moved to the main.tf under modules:

├── env 
│ └── main.tf
├── function
│ ├── http_trigger.js
│ └── http_trigger.zip
└── modules
└── main
└── main.tf

Here the service address is: module.main.google_project_service.cloud-functions

And for a while (while you were in development) was ok. But then, one day, you went to production… where the tfstate still had the service under the old address… so terraform said: “hey, dude, I will destroy your service resource (disable) and then I will create it again (enable)”. To do this all resources dependent on this one needs to be destroyed as well.

So, what to do?

The solution

You have a real activated service. And in the tfstate you have a resource (google_project_service.cloud-functions) that is not in your tf files (so it will be destroyed) and in your tf files a new resource (module.main.google_project_service.cloud-functions) that needs to be created… but wait, that you already have in the Google Cloud infrastructure!

So, delete the old resource from the tfstate, import it again under the new address… and voilà, you can have a beer and a success!

First delete the old resource from the tfstate:

terraform state rm google_project_service.cloud-functions

Then import the actual service as resource into your tfstate:

terraform import google_project_service.cloud-functions your-proyect-id/cloudfunctions.googleapis.com

(change the project ID)

Ok, now you can run your terraform again a enjoy watching it not trying to delete your service!

Conclusion

Don’t panic and carry a towel…

Originally published at http://juanmatiasdelacamara.wordpress.com on November 10, 2020.

--

--