Here is my scenario: I had an EC2 that lacked a permission (create tag):
Time (0). I updated the IAM role on the role (outside of Terraform).
Time(1). I updated my Terraform code to include the create tag permission in the IAM role.
Time(3). I ran terraform plan, and there’s nothing to apply.
Time(4). I go back to the console and remove the manual changes to the IAM role (remove create tag permission).
Time(5). I reran the Terraform plan, and it wants to change my IAM role.
So, in this case, the State File is not used. It does get updated after the apply (after time 5).
So, when is the State File used, when is it not when determining what to create,update, destroy?
Every time you run your plan and if there a existing state, the terraform will confront your provider vs your state.
Time(1). I updated my Terraform code to include the create tag permission in the IAM role.
Time(3). I ran terraform plan, and there’s nothing to apply.
Between this events, terraform check your state and detect “no drifts” because you fix your change out of terraform in your new code.
Time(5). I reran the Terraform plan, and it wants to change my IAM role.
Terraform detect drift between in your state and your code and will apply change.
I have a follow up question about when Terraform decides to change things.
Here is the scenario:
Time 0: I update a resource via the console manually (I updated volume tags in this case). So, in this case, the State File and the Terraform Code matched the old tags.
Time 1: I ran Terraform plan. The Terraform plan wanted to revert the volume tags back to the original state.
Time 2: I changed the Terraform code to match my manual changes. This time the Terraform plan indicated no changes.
So, in this case, Terrform decided to change because the current system did not match the Terraform code. It looks like the State File did not play a role here.
In the earlier scenario (IAM roles in that case), the current system state matched the Terraform code, but it did NOT match the State File, and nothing was planned/applied.
In step 4, I reverted the current system to match the State File. So, only difference here was Terraform code did not match the current system. Again, it doesn’t look like
the State File played a role.
I’m still scratching my head about what the State File does.
Think about it this way, if there were no state, how would the provider know which real life AWS instance corresponds to which configuration block? The state stores more than just the configured attributes of each resource instance, it stores everything that the provider needs in order to plan and apply subsequent changes, as well as giving Terraform a way to map the desired configuration to the state of each instance.
Thank you. I went down this rabbit hole because I think I ran into a Terraform bug (EBS data volume tags). Normally, I wouldn’t be updating things manually, but I’m trying to compensate for some drift I’m seeing. Thank you guys. Ed