Repository navigation
fix: resolve JIT workdir path for !terraform.state, !terraform.output, and atmos.Component - #2328
Conversation
ReadTerraformBackendLocal always used the static formula TerraformDirAbsolutePath + component_name to find state files. JIT workdir components provision to .workdir/terraform/<stack>-<component>/ so !terraform.state always returned 'not provisioned' for them. Add resolveLocalBackendComponentPath helper with three-step resolution: 1. _workdir_path fast path (set by provisioner during apply) 2. BuildPath derivation when provision.workdir.enabled: true 3. Static fallback for non-JIT components (unchanged behavior) Fixes cloudposse#2167
Regression test for cloudposse#2167. Pre-populated state file at .workdir/terraform/test-producer/ terraform.tfstate.d/test-producer/terraform.tfstate so the test requires no network access or terraform run.
…test The .workdir/terraform.tfstate.d path matches *.tfstate.* in .gitignore. Force-add so the integration test fixture is available in CI. Related to cloudposse#2167
|
Tip Atmos Pro
No affected stacks workflow was detected for this pull request. |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds JIT workdir resolution and coordinated provisioning for Terraform outputs/state. Resolver prefers explicit Changes
Sequence Diagram(s)sequenceDiagram
participant Caller as Caller (describe / executor)
participant Exec as Output.Executor
participant SF as singleflight.Group
participant Prov as WorkdirProvisioner
participant Src as SourceAutoProvision
participant WD as ProvWorkdir
participant TF as Terraform Runner
Caller->>Exec: request outputs/state for component
Exec->>SF: Do(key = stack\0component)
alt leader
SF->>Prov: Provision(ctx, atmosConfig, componentConfig, authCtx)
Prov->>Src: AutoProvisionSource (if component has source)
Src-->>Prov: hydrated source files
Prov->>WD: ProvisionWorkdir (copy/sync to .workdir)
WD-->>Prov: workdir path (or error)
Prov-->>SF: result (success + reprovision flag) or error
else waiter
SF-->>Exec: wait for leader result (or return ctx.Err())
end
Exec->>TF: terraform init / terraform output (using selected workdir)
TF-->>Exec: outputs/state (or error)
Exec-->>Caller: resolved outputs/state (or propagated error)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@internal/terraform_backend/terraform_backend_local_test.go`:
- Around line 236-237: The inline comments near the BuildPath example and the
workspace example (the lines showing "BuildPath(\"tempDir\", \"terraform\",
\"null-label\", \"demo\", sections) →
tempDir/.workdir/terraform/demo-null-label" and "workspace \"demo\" →
terraform.tfstate.d/demo/terraform.tfstate") are missing trailing periods;
update those comment lines (and the other flagged comment lines around the same
block: the ones at the same examples referenced in the diff and at lines flagged
252, 282, 284) to end with a period so they satisfy the godot linter requirement
for comments ending with a period.
In `@internal/terraform_backend/terraform_backend_local.go`:
- Line 33: The code currently takes only the stamped _workdir_path
(componentPath from resolveLocalBackendComponentPath) and returns early if the
state is missing, but per the documented fallback order
ReadTerraformBackendLocal should try three candidates: 1) stamped _workdir_path,
2) derived workdir (from deriveWorkdir or similar logic that uses atmosConfig
and componentSections), and 3) the static fallback path; update the logic in
ReadTerraformBackendLocal to build a candidate list with componentPath first,
then the derived workdir, then the static fallback, and iterate over candidates:
for each candidate check for the state file and return the found backend; only
return nil after all candidates are tried. Make sure to keep
resolveLocalBackendComponentPath/componentPath as the first candidate and
reference the existing derive/construct functions used for the other two paths
so no new path-building logic is duplicated.
In `@tests/fixtures/scenarios/terraform-state-jit-workdir/atmos.yaml`:
- Around line 19-20: The fixture hardcodes a Unix-only log sink by setting
logs.file: "/dev/stderr" in atmos.yaml; remove the logs.file entry (leave just
the logs block or omit logs entirely) so the scenario uses the default portable
logger instead of a platform-specific path. Update the atmos.yaml fixture to
drop the logs.file key (or replace it with a platform-agnostic setting) so tests
run on Windows, macOS, and Linux.
In `@tests/yaml_func_terraform_state_jit_test.go`:
- Around line 29-30: The two inline comment lines "// consumer has: vars.foo:
!terraform.state producer test foo" and "// This resolves producer's state file
from .workdir/terraform/test-producer/" must be terminated with periods to
satisfy the godot linter; update those comment strings so each ends with a
period (e.g., add a trailing "." to the first comment and ensure the second
already ends with one).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: c5200d3f-0a88-45cc-abd0-3256a9e77b2d
⛔ Files ignored due to path filters (1)
tests/fixtures/scenarios/terraform-state-jit-workdir/.workdir/terraform/test-producer/terraform.tfstate.d/test-producer/terraform.tfstateis excluded by!**/*.tfstate
📒 Files selected for processing (6)
internal/terraform_backend/terraform_backend_local.gointernal/terraform_backend/terraform_backend_local_test.gotests/fixtures/scenarios/terraform-state-jit-workdir/atmos.yamltests/fixtures/scenarios/terraform-state-jit-workdir/components/terraform/mock/main.tftests/fixtures/scenarios/terraform-state-jit-workdir/stacks/deploy/test.yamltests/yaml_func_terraform_state_jit_test.go
!terraform.state local backend!terraform.state backend.tf.json: ... no such file or directory
…dering, test coverage
Extract workdir provisioning, output processing, utility helpers, and runner methods from executor.go into dedicated files; executor.go now sits at 563 lines.
…lt in local backend Adds a path-traversal guard that rejects _workdir_path values escaping BasePath (falling through to the BuildPath-derived path), and absolutizes the BuildPath result so CWD-relative BasePath values work correctly.
Replace the LoadOrStore-sentinel-before-provision pattern with singleflight.Group so concurrent goroutines block until the single in-flight Provision call completes, eliminating the window where a racing goroutine could proceed to terraform init on an incomplete workdir during parallel atmos describe stacks runs.
…concurrent test Replace time.Sleep-based goroutine synchronization in TestEnsureWorkdirProvisioned_ConcurrentCallsBlockUntilComplete with an atomic entered counter so the gate releases only after the leader is confirmed inside Provision. Add comment at the config.InitRunReconfigure mutation site explaining that only the leading goroutine's config is updated by design.
…ent symlink caveat
|
Review pls |
|
🧠 Learnings used✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (1)
pkg/provisioner/source/vendor.go (1)
57-81: Harden temp staging path handling.Removing the reserved temp directory before reuse weakens path ownership guarantees. Prefer creating a private temp root and passing a non-existent child path to the downloader.
♻️ Safer staging-path pattern
- tempDir, err := os.MkdirTemp("", "atmos-source-*") + tempRoot, err := os.MkdirTemp("", "atmos-source-*") if err != nil { return errUtils.Build(errUtils.ErrCreateTempDir). WithCause(err). WithExplanation("Failed to create temporary directory for download"). Err() } - // Remove the empty directory so go-getter can create it as a symlink (for - // file:// URIs) or recreate it as a real directory (for remote URIs). - if removeErr := os.Remove(tempDir); removeErr != nil && !os.IsNotExist(removeErr) { - return errUtils.Build(errUtils.ErrCreateTempDir). - WithCause(removeErr). - WithExplanation("Failed to prepare temporary directory for download"). - Err() - } - defer os.RemoveAll(tempDir) + defer os.RemoveAll(tempRoot) + tempDir := filepath.Join(tempRoot, "fetch-dst") // must not exist for file:// symlink behavior.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/provisioner/source/vendor.go` around lines 57 - 81, The current code calls os.MkdirTemp to reserve tempDir then immediately removes it (using os.Remove) which loses ownership guarantees; instead create a private temp root (e.g., tmpRoot := os.MkdirTemp("", "atmos-source-root-*") ), keep that directory, and pass a non-existent child path inside it (e.g., stagingPath := filepath.Join(tmpRoot, "staging-"+uuid) or similar) to the downloader so go-getter can create the child (symlink or directory) without deleting the reserved root; ensure error handling cleans up tmpRoot on failures and replace references to tempDir and the os.Remove/removeErr logic with this tmpRoot + non-existent child pattern, updating any subsequent cleanup and vendor.CopyToTarget usage to operate from the child path.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@internal/terraform_backend/terraform_backend_local_test.go`:
- Around line 484-495: The test currently allows a nil fallback read which masks
a broken fallback; update the subtest using tb.ReadTerraformBackendLocal(config,
§ions, nil) to require that content is non-nil (use require.NotNil(t,
content) or equivalent) before calling tb.ProcessTerraformStateFile, then parse
and assert the resulting map contains id == "eg-test-demo" (use require.NoError
on ProcessTerraformStateFile and assert.Equal on result["id"]). Reference
ReadTerraformBackendLocal, tb.ProcessTerraformStateFile, config and sections
when locating where to tighten the assertion.
In `@internal/terraform_backend/terraform_backend_local.go`:
- Around line 118-127: The code currently returns workdirPath when
filepath.Abs(atmosConfig.BasePath) fails, allowing an unvalidated derived path
to be used; instead, modify the block around filepath.Abs(atmosConfig.BasePath)
so that on errBase != nil you do NOT return workdirPath but fall through to the
static path logic (i.e., remove the early return), and log the absolutization
error (including errBase) with context (e.g., using log.Debug or log.Error) so
ReadTerraformBackendLocal does not trust an unverifiable workdirPath derived
from atmosConfig.BasePath.
In `@pkg/terraform/output/config_test.go`:
- Around line 439-440: The tests in pkg/terraform/output/config_test.go compare
OS paths against hardcoded POSIX-style literals (e.g., the variable path vs
"components/terraform" and the POSIX absolute path around lines 448-449); update
the assertions to be platform-safe by normalizing both sides with filepath.Clean
and converting separators (use filepath.ToSlash or filepath.FromSlash
consistently) or construct expected paths with filepath.Join/filepath.Abs so
comparisons don't depend on '/' separators; specifically change the
assert.NotContains(t, path, "components/terraform", ...) to compare
filepath.ToSlash(filepath.Clean(path)) against "components/terraform" (or build
expected via filepath.Join("components","terraform")), and replace the hardcoded
POSIX absolute path fixture with one built via filepath.Join and filepath.Abs
(or filepath.FromSlash) so the test passes on Windows, macOS, and Linux.
In `@pkg/terraform/output/executor_output.go`:
- Line 75: Replace the dynamic fmt.Errorf(...) return with the repository's
static sentinel error from errors/errors.go: wrap that sentinel (e.g.,
errors.ErrEvaluateOutput or the appropriate sentinel defined in
errors/errors.go) and attach the errContext as structured context/hint (using
the project's error helper such as errors.WithHint/WithContext/Wrap*). Locate
the return that currently does "return nil, false, fmt.Errorf(\"failed to
evaluate %s: %w\", errContext, err)" in executor_output.go and change it to
return the sentinel wrapped with the original err (as the cause) and include
errContext via the project's structured hint API so the error uses the static
sentinel while preserving the underlying error and context.
- Around line 33-35: The current debug log in executor_output.go includes a
summarized output value via summarizeValue(s) which can leak secrets; remove the
value_summary argument from the log.Debug call and instead log only structural
metadata (e.g., the output key, its data type from reflect.TypeOf(s) or a helper
like inferType(s), and the size/length of the payload via len/size helper).
Update the log invocation near summarizeValue(s) and any related variable
(summarizeValue) usage so logs contain only key, type, and size, not the value
or its summary.
---
Nitpick comments:
In `@pkg/provisioner/source/vendor.go`:
- Around line 57-81: The current code calls os.MkdirTemp to reserve tempDir then
immediately removes it (using os.Remove) which loses ownership guarantees;
instead create a private temp root (e.g., tmpRoot := os.MkdirTemp("",
"atmos-source-root-*") ), keep that directory, and pass a non-existent child
path inside it (e.g., stagingPath := filepath.Join(tmpRoot, "staging-"+uuid) or
similar) to the downloader so go-getter can create the child (symlink or
directory) without deleting the reserved root; ensure error handling cleans up
tmpRoot on failures and replace references to tempDir and the
os.Remove/removeErr logic with this tmpRoot + non-existent child pattern,
updating any subsequent cleanup and vendor.CopyToTarget usage to operate from
the child path.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: ef4c69b3-e830-4c4e-97c0-6781ac1fd306
📒 Files selected for processing (32)
go.modinternal/terraform_backend/terraform_backend_local.gointernal/terraform_backend/terraform_backend_local_test.gopkg/config/load.gopkg/config/load_config_args.gopkg/config/load_test.gopkg/provisioner/source/provision_hook.gopkg/provisioner/source/vendor.gopkg/provisioner/workdir/workdir.gopkg/schema/schema.gopkg/terraform/output/config.gopkg/terraform/output/config_test.gopkg/terraform/output/executor.gopkg/terraform/output/executor_output.gopkg/terraform/output/executor_runner.gopkg/terraform/output/executor_test.gopkg/terraform/output/executor_utils.gopkg/terraform/output/executor_workdir.gopkg/terraform/output/mock_executor_test.gotests/fixtures/scenarios/terraform-output-jit-workdir/.gitignoretests/fixtures/scenarios/terraform-output-jit-workdir/atmos.yamltests/fixtures/scenarios/terraform-output-jit-workdir/components/terraform/mock/main.tftests/fixtures/scenarios/terraform-output-jit-workdir/source-modules/mock-alt/main.tftests/fixtures/scenarios/terraform-output-jit-workdir/stacks/deploy/test.yamltests/fixtures/scenarios/terraform-state-jit-workdir/atmos.yamltests/fixtures/scenarios/terraform-state-jit-workdir/stacks/deploy/test.yamltests/preconditions.gotests/yaml_func_terraform_output_jit_test.gotests/yaml_func_terraform_source_jit_test.gotests/yaml_func_terraform_state_jit_test.gowebsite/docs/cli/configuration/components/terraform.mdxwebsite/docs/cli/environment-variables.mdx
✅ Files skipped from review due to trivial changes (9)
- tests/fixtures/scenarios/terraform-output-jit-workdir/.gitignore
- tests/fixtures/scenarios/terraform-output-jit-workdir/components/terraform/mock/main.tf
- go.mod
- tests/fixtures/scenarios/terraform-state-jit-workdir/atmos.yaml
- tests/fixtures/scenarios/terraform-output-jit-workdir/stacks/deploy/test.yaml
- tests/fixtures/scenarios/terraform-output-jit-workdir/atmos.yaml
- tests/fixtures/scenarios/terraform-state-jit-workdir/stacks/deploy/test.yaml
- website/docs/cli/environment-variables.mdx
- tests/fixtures/scenarios/terraform-output-jit-workdir/source-modules/mock-alt/main.tf
- Drop value_summary from debug log in processOutputs; outputs can contain secrets and summarizeValue truncates at 100 chars which still leaks short single-line secrets. Log only value_size_bytes. - Wrap dynamic fmt.Errorf in extractYqValue with new static sentinel ErrEvaluateOutput per project error handling policy. - Fix unverified derived workdir path returned when filepath.Abs on BasePath fails; fall through to static path instead. - Make config_test path assertion cross-platform via filepath.ToSlash and replace hardcoded /tmp/mock with t.TempDir() for Windows. - Clarify traversal-test comment explaining why nil is a valid result when the workspace prefix consumes a .. level.
|
CodeRabbit (@coderabbitai) again plz |
|
🧠 Learnings used✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (3)
internal/terraform_backend/terraform_backend_local_test.go (1)
423-426: Prefert.Chdiroveros.Chdir+ deferred restore.Atmos's extended
*testing.Tprovidest.Chdir(), which handles restoration automatically and is used consistently across the repo. Safer against panic paths and a bit tidier.🔧 Proposed refactor
- // Change CWD to tempDir so relative BasePath "." resolves there. - origDir, err := os.Getwd() - require.NoError(t, err) - require.NoError(t, os.Chdir(tempDir)) - defer func() { _ = os.Chdir(origDir) }() + // Change CWD to tempDir so relative BasePath "." resolves there. + t.Chdir(tempDir)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/terraform_backend/terraform_backend_local_test.go` around lines 423 - 426, Replace the manual working-directory swap using os.Getwd(), os.Chdir(tempDir), and the deferred restore with the testing helper t.Chdir(tempDir); specifically remove the origDir variable, the require.NoError(t, os.Chdir(tempDir)) call and the deferred func that restores the directory, and call t.Chdir(tempDir) instead so the extended *testing.T implementation handles restoration and panic-safe cleanup for this test.internal/terraform_backend/terraform_backend_local.go (2)
101-112: Nit:atmos_componentis resolved twice.
getAtmosComponentInstanceFromSectionsextractsatmos_component(falling back toGetTerraformComponent), thenprovWorkdir.BuildPathindependently re-readsatmos_componentfrom the same map and overrides the passedcomponentwhen present. The net behavior is correct but the double-lookup is a little confusing — a future refactor toBuildPathcould silently change semantics here. Optional: pass the base component name and letBuildPathown theatmos_componentoverride entirely, or skip the local helper and letBuildPathdo the resolution.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/terraform_backend/terraform_backend_local.go` around lines 101 - 112, The code resolves atmos_component twice: once via getAtmosComponentInstanceFromSections(sections) and again inside provWorkdir.BuildPath, which can lead to confusing/fragile semantics; fix by choosing one source of truth — either pass the base component name through and let BuildPath perform any atmos_component override (change the call to provWorkdir.BuildPath to pass the original base component instead of a resolved one), or remove the secondary lookup in BuildPath and trust the component returned by getAtmosComponentInstanceFromSections; update the implementation of either getAtmosComponentInstanceFromSections or provWorkdir.BuildPath (and any callers) so only a single lookup (using the atmos_component key or GetTerraformComponent fallback) determines the component.
91-92: Windows path containment check is case-sensitive; consider usingfilepath.Relfor case-insensitive comparison.Lines 92 and 121 use
strings.HasPrefix(absPath, absBase+sep)which is case-sensitive. On Windows, ifabsBaseandabsPathdiffer in drive letter or directory casing (e.g.,C:\Projectvsc:\project\...), the check fails despite the paths being equivalent. Althoughfilepath.Absis used to resolve paths, it doesn't normalize case on Windows.Use
filepath.Rel(absBase, absPath)and check that the result doesn't start with".."or"..\"—filepath.Relinternally uses case-insensitive comparison on Windows viafilepath.sameWord.Note: Existing tests verify path traversal rejection but don't cover Windows case-sensitivity scenarios.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/terraform_backend/terraform_backend_local.go` around lines 91 - 92, The current containment check using strings.HasPrefix(absP, absBase+sep) (and the absP == absBase special-case) is case-sensitive and can fail on Windows; replace these checks with filepath.Rel(absBase, absP) and ensure the returned relative path does not start with ".." (or is exactly "..") to determine containment, treating equality when Rel returns "." as inside; do the same replacement for the second occurrence around line 121 so both uses of absP/absBase use filepath.Rel instead of strings.HasPrefix/sep.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@internal/terraform_backend/terraform_backend_local_test.go`:
- Line 347: The inline comment for the map entry keyed by "_workdir_path" in
terraform_backend_local_test.go is missing a trailing period; update the comment
after workdirPath (the comment currently reads "explicit path set by
provisioner") to end with a period ("explicit path set by provisioner.") so it
complies with the godot linter; locate the map literal containing
"_workdir_path" and adjust that comment accordingly.
---
Nitpick comments:
In `@internal/terraform_backend/terraform_backend_local_test.go`:
- Around line 423-426: Replace the manual working-directory swap using
os.Getwd(), os.Chdir(tempDir), and the deferred restore with the testing helper
t.Chdir(tempDir); specifically remove the origDir variable, the
require.NoError(t, os.Chdir(tempDir)) call and the deferred func that restores
the directory, and call t.Chdir(tempDir) instead so the extended *testing.T
implementation handles restoration and panic-safe cleanup for this test.
In `@internal/terraform_backend/terraform_backend_local.go`:
- Around line 101-112: The code resolves atmos_component twice: once via
getAtmosComponentInstanceFromSections(sections) and again inside
provWorkdir.BuildPath, which can lead to confusing/fragile semantics; fix by
choosing one source of truth — either pass the base component name through and
let BuildPath perform any atmos_component override (change the call to
provWorkdir.BuildPath to pass the original base component instead of a resolved
one), or remove the secondary lookup in BuildPath and trust the component
returned by getAtmosComponentInstanceFromSections; update the implementation of
either getAtmosComponentInstanceFromSections or provWorkdir.BuildPath (and any
callers) so only a single lookup (using the atmos_component key or
GetTerraformComponent fallback) determines the component.
- Around line 91-92: The current containment check using strings.HasPrefix(absP,
absBase+sep) (and the absP == absBase special-case) is case-sensitive and can
fail on Windows; replace these checks with filepath.Rel(absBase, absP) and
ensure the returned relative path does not start with ".." (or is exactly "..")
to determine containment, treating equality when Rel returns "." as inside; do
the same replacement for the second occurrence around line 121 so both uses of
absP/absBase use filepath.Rel instead of strings.HasPrefix/sep.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 2b2e8a93-b7cb-4558-a87e-a102fa9fa24e
📒 Files selected for processing (5)
errors/errors.gointernal/terraform_backend/terraform_backend_local.gointernal/terraform_backend/terraform_backend_local_test.gopkg/terraform/output/config_test.gopkg/terraform/output/executor_output.go
✅ Files skipped from review due to trivial changes (2)
- errors/errors.go
- pkg/terraform/output/config_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- pkg/terraform/output/executor_output.go
Address CodeRabbit review feedback at line 347.
The new auto_provision_workdir_for_outputs config field (added in previous commits on this branch) is surfaced by describe config and describe component commands. Regenerate affected snapshots so CI acceptance tests pass. Environmental noise (pager, github_token, OS/arch) in the regenerated output is normalized by existing sanitize/diff rules in the test cases.
Two related CI fixes: 1. Golden snapshots regenerated without GITLAB_TOKEN in environment. The previous regeneration (084daca) was run with GITLAB_TOKEN set, which baked "<MASKED>" into the committed snapshots. CI does not set GITLAB_TOKEN, so its output contained empty strings — mismatching the committed golden. Regenerating with GITLAB_TOKEN unset aligns the snapshots with the CI environment. The secrets-masking snapshot is also updated to include the new auto_provision_workdir_for_outputs field. 2. tests/yaml_func_terraform_source_jit_test.go built file:// URIs as "file://" + slashified-abs-path. On Unix this produced three-slash URIs (file:///tmp/...), which go-getter accepts. On Windows the slashified drive path starts with "D:/" so the result was "file://D:/..." — two slashes with "D:" parsed as host, breaking the FileGetter on Windows CI. Introduce a toFileURI helper that always prefixes a leading slash before the path, yielding the RFC 8089 form (file:///D:/... on Windows, file:///tmp/... on Unix).
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #2328 +/- ##
========================================
Coverage 77.28% 77.29%
========================================
Files 1080 1084 +4
Lines 102239 102358 +119
========================================
+ Hits 79019 79119 +100
- Misses 18868 18879 +11
- Partials 4352 4360 +8
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
|
zack-is-cool please check the Windows tests. |
go-getter's FileGetter creates a symlink at the destination when fetching file:// URIs. Windows CI runners lack SeCreateSymbolicLinkPrivilege, so the fetch fails silently (spinner suppresses non-TTY error output), leaving the workdir directory created but unhydrated. Linux and macOS continue to cover the underlying JIT-workdir-from-source behavior. Real-world source URIs are remote (github.com, s3://) where go-getter copies rather than symlinks, so production Windows usage is unaffected. Pattern matches pkg/downloader/git_getter_test.go which already skips symlink tests on unsupported platforms.
Claude is telling me Will try what you said to see if it picks something else up |
go-getter's FileGetter creates a symlink at the destination when the source URI points to a directory. Windows CI runners typically lack SeCreateSymbolicLinkPrivilege, so the symlink creation fails silently and the workdir ends up empty. Replace the direct directory URI with a .tar.gz archive built at test time from mock-alt/. go-getter extracts archives to real files on every platform, restoring Windows coverage without the symlink requirement. This also removes the runtime-based skip added in 17f20f9.
|
Logic behind creating the tarball in the test |
|
zack-is-cool please resolve the conflicts |
df4beff
into
cloudposse:main
|
These changes were released in v1.216.0-rc.2. |
What
Bug fix PR. Makes
!terraform.state,!terraform.output, andatmos.Componentwork correctly for JIT workdir components (provision.workdir.enabled: true). All three were silently broken in ways that only surfaced at runtime.Four fixes:
!terraform.statepath resolution — resolves state path from.workdir/terraform/<stack>-<component>/instead of the static source directory JIT components never write state to.!terraform.output/atmos.Componentauto-provision — provisions the JIT workdir beforeterraform initso output references work on any machine, not just ones with a pre-existing workdir from a prior apply.source.uricomponents,!terraform.outputnow hydrates from the source URI before init. Also fixesextractComponentNamefallback and a go-getterFileGetterdst-must-not-exist invariant.ui.ClearLine()before status writes prevents the bubbletea spinner from leaving leading whitespace on provisioner messages.Correctness & security fixes:
sync.Map.Load+Storereplaced withLoadOrStoreinside the singleflight closure, eliminating the window where two goroutines could both enterProvision.singleflight.DoChan+selectso waiters with cancelled contexts exit immediately. Addedcontext.WithoutCancelso leader cancellation doesn't abort shared provisioning work.extractComponentPathverifies the derived workdir path stays withinfilepath.Abs(basePath)before returning it; escaping paths fall back tocomponentPath. Mirrors the existing guard interraform_backend_local.go.ErrWorkdirProvisionnow includes the full YAML path and env var to disable auto-provisioning.loadConfigFromCLIArgsenv var bug —setEnv(v)was missing on the--config/--config-pathcode path, silently ignoring allATMOS_*overrides when config was loaded from CLI args.auto_provision_workdir_for_outputsandATMOS_COMPONENTS_TERRAFORM_AUTO_PROVISION_WORKDIR_FOR_OUTPUTSadded to the config/env var reference docs.Why
JIT workdir components write their Terraform files to
.workdir/terraform/<stack>-<component>/via abefore.terraform.inithook — but that hook only fires during directatmos terraformcommands, not YAML function evaluation. Three distinct silent failures resulted:!terraform.statelooked in the source directory where JIT components have no state — unconditional failure.!terraform.outputcomputed the correct workdir path but never populated the directory before callingterraform init— fails with "no such file or directory" on any cold machine.!terraform.output+source.uri— even with Fix 2,ProvisionWorkdironly copies local files. Source-provisioned components needAutoProvisionSourcefirst, which only fires in the hook system the output executor never reaches.Note on Fix 3 (source.uri components)
!terraform.outputagainst a source-provisioned component with a cold workdir will fetch fromsource.uri— the same credentials already needed foratmos terraform apply. The fetch is cached per(stack, component)pair per process.Set
auto_provision_workdir_for_outputs: false(orATMOS_COMPONENTS_TERRAFORM_AUTO_PROVISION_WORKDIR_FOR_OUTPUTS=false) to disable Fixes 2 and 3.For state-only reads, prefer
!terraform.state— no init, no source fetch, no terraform binary required.Migration
No breaking changes. Previously-failing commands now work.
Resolves #2167
Summary by CodeRabbit
New Features
Security / Bug Fixes
Documentation
Tests