opentofu: Ensure tofu init Creates State File for Remote Backends if Missing
Community note
[!TIP] 👋 Hi there, OpenTofu community! The OpenTofu team prioritizes issues based on upvotes. Please make sure to upvote this issue and describe how it affects you in detail in the comments to show your support.
OpenTofu Version
OpenTofu v1.9.0
The problem in your OpenTofu project
Currently, tofu init does not create a state file when using remote backends (e.g., S3, GCS, PostgreSQL). This behavior is
- inconsistent with the local backend, where init creates an empty terraform.tfstate file immediately.
- innately counterintuative, as
initactions should do everythin necessary to fully initialise the thing.
This causes issues in CI/CD pipelines and onboarding workflows because:
tofu planfails if no state file exists, requiring a manual or scripted workaround.- Users must apply a “dummy” resource (e.g.,
null_resource) just to force state creation. - Teams must manually check for state existence before running OpenTofu, adding unnecessary complexity.
This behavior is confusing and poorly documented, making it difficult for new users and automation workflows.
Attempted Solutions
Attempted Solutions
Running tofu init Alone
Expected behavior:
tofu init -input=false \
-backend-config="bucket=my-bucket" \
-backend-config="key=my-project/tofu.tfstate" \
-backend-config="region=us-east-1"
Expected: State file is created in the backend Actual: No state file is created
Running tofu plan After init
tofu plan -input=false -out=tfplan
Expected: Plan runs successfully Actual:
Error: No stored state was found for the given workspace in the given backend.
Plan fails because no state file exists.
Adding an Empty Backend Block in HCL
terraform {
backend "s3" {}
}
Expected: State file is created on init Actual: No state file is created
Workaround: Manually Applying a null_resource to Force State Creation
terraform {
backend "s3" {}
}
resource "null_resource" "bootstrap" {}
tofu apply -auto-approve
This works, but it’s a hack.
Limitations of These Workarounds
- Forces users to manually apply an empty resource just to create a state file.
- Requires extra logic in CI/CD pipelines to check for state existence before plan.
- Breaks the expectation that
tofu initfully prepares the backend.
We need a cleaner, built-in solution where OpenTofu automatically creates an empty state file on init if none exists. 🚀
Proposal
Modify tofu init to create an initial state file in the remote backend if one does not already exist. This would align the behaviour of remote backends with the local backend, where tofu init immediately creates an empty terraform.tfstate file.
Suggested Implementation
- When
tofu initis executed, it should check if a state file exists in the configured remote backend. - If no state file exists,
tofu initshould create an empty or minimally structured state file. - This behaviour should be consistent across all supported remote backends (e.g., S3, GCS, PostgreSQL).
- Ensure this operation does not overwrite an existing state file or introduce unintended side effects.
Benefits
- Improves CI/CD Automation: Eliminates the need for workarounds such as pre-checking or creating a dummy resource to initialise state.
- Reduces Onboarding Complexity: New users no longer need to manually bootstrap the state.
- Aligns with Local Backend Behaviour: Ensures consistency between local and remote backends.
- Enhances User Experience: Reduces confusion and the need for undocumented manual steps.
Workarounds and Alternatives
Since tofu init does not create a state file in remote backends, users must implement manual or scripted workarounds to avoid errors during tofu plan and tofu apply.
Manually Running a “Dummy” Apply
Users must create and apply a placeholder resource, such as a null_resource, just to generate the initial state file.
resource "null_resource" "bootstrap" {}
tofu init
tofu apply -auto-approve
Problems:
- Introduces unnecessary changes to the state.
- Requires cleanup (i.e., removing the dummy resource after initialisation).
- Adds friction to onboarding and automation.
Checking for State Before Running OpenTofu
Users write scripts to check for the existence of the state file before running tofu plan.
if ! aws s3 ls s3://my-bucket/path/to/state.tfstate >/dev/null 2>&1; then
echo "{}" | aws s3 cp - s3://my-bucket/path/to/state.tfstate
fi
Problems:
- Backend-specific and requires different implementations for S3, GCS, PostgreSQL, etc.
- Adds complexity to CI/CD pipelines.
- Requires additional permissions to create an empty state file
Using tofu import as a State Bootstrap
Some users work around the issue by running tofu import to generate an initial state.
Problems:
- Requires a real resource to import, making it impractical for new projects.
- Does not help when starting from an empty configuration.
Why This Proposal Is Better
- Removes the need for unnecessary workarounds. tofu init would seamlessly ensure the state file exists without manual intervention.
- Simplifies automation. CI/CD pipelines can execute tofu init && tofu plan without extra checks or scripts.
- Improves consistency. The behaviour of tofu init would align across local and remote backends, reducing confusion.
- Reduces errors. New users would not encounter unexpected failures due to missing state.
This change would make OpenTofu more intuitive, particularly for teams adopting it in automated environments.
Possible Middle Ground: tofu init -force-state
I do appreciate that I am proposing the change of default behaviour, so if that is not possible, the addition of the -force-state flag would suffice. This would mean that tofu init stays as it is, but tofu init -force-state would check if the state exists, and if not, create an empty one.
Considerations:
- It would need to be safe to include -force-state every time to ensure that reusable workflows (or similar) can be used.
- Lineage would need to be managed from the outset.
- The “Unable to find remote state” error should be modified to “Unable to find remote state! State files are normally created by tofu apply; would tofu init -force-state help you?”
This would still allow me to delete my silly boostrap bodge, while also avoiding any impact on anyone that might currently be relying on tofu init not creating a state file.
References
No response
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Reactions: 3
- Comments: 17 (9 by maintainers)
Side note, I do find it amazing the things that nerds (like me) gather opinions on. If I walked into a pub and asked a normie “what is your opinion on
terraform_remote_state?” I would be shunned 😂Thanks for sharing what you learned, @jamesgeddes!
I assume that what you were doing there is running
tofu show tfplan, which indeed does unfortunately overload its positional argument to allow either a state snapshot file or a save plan file and tries to “do the right thing” by parsing both ways and taking the one that works.Of course, if neither works then it doesn’t really know what you intended to do, and so it returns this low-quality error message describing both of the failures and hopes that you know which of the two kind of files you passed. 😖
Interestingly, the code does seem to try to sniff for a few common error types that might imply what kind of file it seemed to be:
https://github.com/opentofu/opentofu/blob/9a86d86f4d2f3d43ce6078d25ba5d3d262aec690/internal/command/show.go#L251-L309
…but “no such file or directory” is just one of the generic error types from Go’s
package os, and of course it can’t give any information about what kind of file it was intended to be, so this just fell through to the most generic error diagnostic that shrugs 🤷 and shows all of the errors from all of the different possibilities it tried.@apparentlymart I think you are right. I was hitting the “state file not found” error, which was preventing the apply from completing and creating a state.
At the moment I am initialising my envs in GitHub actions with a bootstrap config that only contains a null resource. GitHub actions then switches back to the real config and applies that. This feels a bit clunky.