I am new to the Terraform world. I have started working on IaC for Azure using TF.
I have below three queries regarding using TF:
- In case the state file gets accidentally deleted, is there a way to recover/recreate the state file from the current state of the Azure resources?
- In the case of Azure, if one makes some direct changes to the Azure resources from the Azure portal, is there a way to retrofit those changes automatically into the Terraform .tf or state files?
- Is there a way to generate terraform files for any existing Azure resources created directly from the portal?
2
Answers
First of all rules: Is mandatory to have a regular backup of your state file! Try to configure your Terraform backend in a remote place, like Google Cloud Storage
Answering your questions:
terraform import
. Check this document.If someone changes a resource via the Azure portal and if you do a
terraform plan
in your environment, you should check that changes were done outside Terraform. Then you should update your code to match those changes, after applying your code.To clarify, if someone changes your
instance_type = c4.xlarge
and you have at your codeinstance_type = t3.micro
, if you apply your code, that change will be reverted so if you want to stay with instances withc4.xlarge
you should change your code.I don’t use any kind of that tools but I can imagine that they exists.
You should configure Terraform to use a backend that saves every version of your state file, and makes it really difficult to delete the state file. If you are using Azure as the backend, then I believe that would mean enabling Blob versioning, and Soft delete for blobs.
Disclaimer: I don’t use Azure, so there may be more to it than that. On AWS you would enable S3 bucket versioning and MFA delete, and the features I linked appear to be the Azure equivalent.
You would need to run
terraform plan
and examine the output to see how the current Azure resources differ from the Terraform configuration, then update your Terraform configuration untilterraform plan
says there are no changes.There are some tools, like
terraformer
that attempt to do this, but in my experience they are always missing support for tons of features and generally don’t work well at all.