Aditya Garg
Aditya Garg

Reputation: 171

'terraform plan' NOT updating state file

Tried the following:

Resource creation(ec2) using terraform>>manually edit a resource(changed type) from AWS console>>run 'terraform plan'>>shows changes required after doing 'terraform refresh' internally BUT state file is not getting updated?

Looks like some bug.

(article states refresh is done automatically, it should affect the state file?- https://www.terraform.io/docs/cli/commands/plan.html)

I note that Manually running 'terraform refresh' updates the state file to reflect present state of infrastructure(which then would be compared with config file ie desired state).

Upvotes: 2

Views: 14566

Answers (3)

asmath
asmath

Reputation: 216

As per the below documentation link, you can update your state file without making modifications to your infrastructure using the -refresh-only flag for plan and apply operations.

https://developer.hashicorp.com/terraform/tutorials/state/refresh

enter image description here

But when I checked with terraform version 1.66, it's still not working properly

Test Scenario:

  • Created an instance (instanceA) using Terraform resource block.
  • Manually deleted instanceA from the console.

Execution Steps:--

  • Run terraform plan -refresh=false -> No changes expected.
  • Run terraform plan -refresh-only -> Note: Objects have changed outside of Terraform, but it will not make any changes in the terraform.tfstate file.
  • Run terraform refresh -> Removed instanceA from the terraform.tfstate file.
  • Run terraform plan -refresh=false -> Plan: 1 to add, 0 to change, 0 to destroy.
  • Run terraform plan -refresh-only -> No changes. Your infrastructure still matches the configuration.

but -refresh-only option working fine when using it with apply command like this:

$ terraform apply -refresh-only

Would you like to update the Terraform state to reflect these detected changes?
  Terraform will write these changes to the state without modifying any real infrastructure.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes

Upvotes: 0

Ravi Khambhati
Ravi Khambhati

Reputation: 743

As per the latest documentation the plan operation implicitly does refresh unless you specify refresh=false as a parameter.

enter image description here

Upvotes: 2

Aditya Garg
Aditya Garg

Reputation: 171

Thanks @Software Engineer

The second para explicitly mentions that 'state' is not affected. So in summary, its not treated like a normal 'terraform refresh'. IMAGE

https://www.terraform.io/docs/cli/commands/plan.html

Upvotes: 1

Related Questions