If I start out developing a config and using local terraform.state files is there an elegant way of being able to switch between this and using a backend ?. Using override files is one way of doing this that has occurred to me, but I was wondering if there is a better way.
The main case Terraform is designed around here is that you migrate to a remote state backend and then never come back, because from that point on the remote state is the source of truth. If that describes your goals then you can use the following process:
- Add a
backendblock to your root module that previously didn’t have one.
terraform init, which will notice that the backend configuration changed and ask you if you want to automatically migrate. If you say yes then Terraform will write the latest state snapshot to the configured backend and then delete the local state file.
There is no built-in process for repeatedly switching between backends, because changing backend should generally be a very rare operation due to how much coordination it requires with the rest of a team and with other systems interacting with the Terraform state.
However, if you have a more specialized need where that sort of switching is helpful, override files can indeed be one way to achieve it. That’s more a consequence of what override files do than an intentional solution to the use-case, but it can work.
Another situation where this can arise is if you’re developing a module that is intended to be called from other modules rather than being used as a root. In that case, it should typically have no backend configuration at all because the backend configuration is the root module’s responsibility. In order to test modules like that, we typically recommend writing a small wrapper root module that just calls the module to be tested, and then run
terraform init and
terraform apply in that wrapper module. You can then test the shared module in a more realistic environment (where it’s not a root module), and include in the wrapper module any special settings you might need to support testing, such as