Avoid unrelated provider locks when seeding fresh scoped backends
Homelab Main / validate (push) Waiting to run Details
Homelab Main / running-update (push) Blocked by required conditions Details
Homelab Main / debian-ops (push) Blocked by required conditions Details

This commit is contained in:
juvenal.diaz 2026-11-02 22:40:39 -06:00
parent a6268d875b
commit fb2a4673a2
2 changed files with 36 additions and 4 deletions

View File

@ -65,6 +65,7 @@ def safe_error_titles(output):
"Missing required argument", "Duplicate provider configuration",
"Failed to create local state file", "Failed to update workspace",
"Invalid single-argument block definition", "Invalid backend configuration",
"Provider dependency changes detected",
}
clean = re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", output)
found = []
@ -371,14 +372,18 @@ def initialize_scoped_backend(tool, directory, context, name, env, init_args):
verify_backend_metadata(metadata, state)
else:
dependency_lock = directory / ".terraform.lock.hcl"
if before and document(state).get("resources") and not dependency_lock.is_file():
migrated_resources = bool(before and document(state).get("resources"))
if migrated_resources and not dependency_lock.is_file():
raise Refused("A dependency lock file is required before initializing migrated state")
with tempfile.TemporaryDirectory(prefix=f"backend-init-{name}-", dir=context.root) as temporary:
bootstrap = Path(temporary)
(bootstrap / "main.tf").write_text('terraform {\n backend "local" {}\n}\n')
# init also considers providers referenced in state. Preserve
# the real module's locked versions rather than selecting latest.
if dependency_lock.is_file():
# Migrated state references providers and needs their locked
# versions. A fresh backend-only configuration has no provider
# dependencies: copying the real module's lock file there makes
# readonly init fail on the unused provider selections.
# The real module still uses its complete lock file below.
if migrated_resources:
shutil.copyfile(dependency_lock, bootstrap / ".terraform.lock.hcl")
capture([tool, f"-chdir={bootstrap}", "init", "-input=false", "-no-color", "-get=false",
"-lockfile=readonly", *backend_args], env=env, diagnostic_dir=diagnostics)

View File

@ -341,6 +341,33 @@ class ScopedBackendInitializationTests(unittest.TestCase):
self.assertEqual(self.calls[-1][1], f"-chdir={self.module}")
self.assertEqual(original, (self.legacy.read_bytes(), self.state.read_bytes()))
def test_fresh_backend_does_not_copy_unrelated_provider_lock(self):
original = (self.module / ".terraform.lock.hcl").read_bytes()
legacy = self.legacy.read_bytes()
def fresh_sdk(command, **kwargs):
directory = Path(command[1].split("=", 1)[1])
if directory != self.module:
self.assertFalse((directory / ".terraform.lock.hcl").exists())
self.assertFalse((directory / "terraform.tfstate").exists())
self.assertIn("-lockfile=readonly", command)
MODULE.private_write(self.metadata, {"backend": {"type": "local", "config": {"path": str(self.state)}}})
else:
self.assertEqual((directory / ".terraform.lock.hcl").read_bytes(), original)
return ""
for empty_state in (None, '{"version":4,"resources":[]}'):
with self.subTest(empty_state=empty_state):
self.state.unlink(missing_ok=True)
self.metadata.unlink(missing_ok=True)
if empty_state is not None:
self.state.write_text(empty_state)
with patch.object(MODULE, "capture", side_effect=fresh_sdk):
self.initialize()
self.assertEqual(self.legacy.read_bytes(), legacy)
self.assertEqual((self.module / ".terraform.lock.hcl").read_bytes(), original)
self.assertEqual(self.state.read_text() if self.state.exists() else None, empty_state)
def test_wrong_cached_backend_refuses_without_sdk_calls(self):
MODULE.private_write(self.metadata, {"backend": {"type": "local", "config": {"path": str(self.legacy)}}})
with patch.object(MODULE, "capture") as capture: