Should I commit .tfstate files to Git? Ask Question

Should I commit .tfstate files to Git? Ask Question

I am a little bit puzzled on the question whether to commit .tfstate files to Git or not. The Terraform documentation states:

Terraform also put some state into the terraform.tfstate file by default. This state file is extremely important; it maps various resource metadata to actual resource IDs so that Terraform knows what it is managing. This file must be saved and distributed to anyone who might run Terraform. We recommend simply putting it into version control, since it generally isn't too large.

Now, on the other hand, the accepted and upvoted answer on Best practices when using Terraform states:

Terraform config can be used to provision many boxes on different infrastructure, each of which could have a different state. As it can also be run by multiple people this state should be in a centralised location (like S3) but not git.

(Emphasis by the original author, not by me)

Who is right, and if so, why?

ベストアンサー1

There are a few reasons not to store your .tfstate files in Git:

  1. You are likely to forget to commit and push your changes after running terraform apply, so your teammates will have out-of-date .tfstate files. Also, without any locking on these state files, if two team members run Terraform at the same time on the same .tfstate files, you may overwrite each other's changes. You can solve both problems by both a) storing .tfstate files in an S3 bucket using Terraform remote state, which will push/pull the .tfstate files automatically every time you run terraform apply and b) using a tool like terragrunt to provide locking for your .tfstate files.
  2. The .tfstate files may contain secrets. For example, if you use the aws_db_instance resource, you have to specify a database password, and Terraform will store that, in plaintext, in the .tfstate file. This is a bad practice on Terraform's behalf to begin with and storing unencrypted secrets in version control only makes it worse. At least if you store .tfstate files in S3, you can enable encryption at rest (SSL provides encryption while in motion) and configure IAM policies to limit who has access. It's very far from ideal and we'll have to see if the see open issue discussing this problem about it ever gets fixed.

For more info, check out How to manage Terraform state and Terraform: Up & Running, both of which I wrote.

おすすめ記事