I am a newbie in Terraform and trying to understand how State works in Terraform. If I do a plan and then before apply the state of the resources changes manually what will happen?
Lets say I am trying to delete a vm that was deployed using Terraform. I remove the code from my tf file and do a plan. Now before I can apply someone goes in the console and deletes the vm manually. What will happen when I apply?
I did some research on this and my understanding is that there is a drift between the known state and the actual state. Terraform apply will try to get to my desired state.
So first it will create the vm and then destroy it when I do apply. Is this right understanding?
There are two ways you could be running terraform apply. The most basic option is to just run that command. It will then do a plan as part of the process, optionally as you to confirm and then apply the changes listed in the plan.
Alternatively you can save a plan to a file and then specify it during an apply. It would then try to apply just the plan details listed in the file. If it isn’t able to do that (e.g. it is being asked to make a change to a resource which no longer exists) it will fail with an error.
In general good practice would be to make all changes exclusively via Terraform for all resources it manages - often you’d set up permissions to prevent other systems/people from making changes using other mechanisms. You might also use a CI/CD system (such as Jenkins or CircleCI) to apply all the changes, meaning you’d not run terraform apply manually at all.