how to update terraform state with manual change done on resources

Viewed 9843

i had provisioned some resources over AWS which includes EC2 instance as well,but then after that we had attached some extra security groups to these instances which now been detected by terraform and it say's it'll rollback it as per the configuration file.

Let's say i had below code which attaches SG to my EC2

vpc_security_group_ids = ["sg-xxxx"]

but now my problem is how can i update the terraform.tfstate file so that it should not detach manually attached security groups :

I can solve it as below:

  1. i would refresh terraform state file with terraform refresh which will update the state file.
  2. then i have to update my terraform configuration file manually with security group id's that were attached manually

but that possible for a small kind of setup what if we have a complex scenario, so do we have any other mechanism in terraform which would detect the drift and update it

THanks !!

4 Answers

There is no way Terraform will update your source code when detecting a drift on AWS.

The process you mention is right:

  1. Report manual changes done in AWS into the Terraform code
  2. Do a terraform plan. It will refresh the state and show you if there is still a difference

You can use terraform import with the id to import the remote changes to your terraform state file. Later use terraform plan to check if the change is reflected in the code.

This can be achieved by updating terraform state file manually but it is not best practice to update this file manually.

Also, if you are updating your AWS resources (created by Terraform) manually or outside terraform code then it defeats the whole purpose of Infrastructure as Code.

If you are looking to manage complex infrastructure on AWS using Terraform then it is very good to follow best practices and one of them is all changes should be done via code.

Hope this helps.

terraform import <resource>.<resource_name> [unique_id_from_aws]

You may need to temporarily comment out any provider/resource that relies on the output of the manually created resource.

After running the above, un-comment the dependencies and run terraform refresh.

Related