red888
red888

Reputation: 31642

Terraform lock state at the resource level?

I have a tf file that has multiple resources/modules in it and it all uses a single remote state file in s3.

I often target specific modules in the tf file.

If I have locking setup does that mean two people can't make changes at the same time even if they are targeting different modules?

From what I read it seems Terraform locks the entire state file. Does it support resource level locking? Docs didn't seem clear to me on this.

Upvotes: 1

Views: 917

Answers (1)

Radek Simko
Radek Simko

Reputation: 16146

You're right, Terraform does lock the whole state file regardless of what resources you're targeting.

The idea behind this implementation is that there may be references between resources. More precisely an event involving one resource (creation/update/destruction) originally may cause other resources to be created/updated/destroyed. So even apply -target=resource_one.ref_name may result in changes of other resources. All of that should be presented in terraform plan though.

All state operations (incl. locking) are currently implemented on the backend (S3, Consul, TFE, ...) level and the common interface between them isn't as flexible because the common denominator is basically blob of JSON (state file).

If you have two or more independent parts of infrastructure then I'd suggest you to split them apart into either different workspaces or directories. You can leverage terraform state subcommands to do the migration after splitting your config files.

You can also use the terraform_remote_state data source to reference any outputs exposed from any of these parts.

Managing independent parts of your infrastructure in a single state file is not something I'd recommend for a couple of reasons:

  • It doesn't scale very well. As you begin to add more resources, the time it takes to finish terraform plan & apply will increase as Terraform has to check current state of each resource.
  • All critical Terraform commands have blast radius wider than necessary which makes human errors much scarier. e.g. accident terraform destroy will destroy everything, not just one part of your infra.

The -target flag is meant to be used for exceptional circumstances, not for routine operations, as mentioned in the docs.

Upvotes: 1

Related Questions