Skip to content

fix(provisioner): make coder_env and coder_script iteration deterministic#22706

Draft
kacpersaw wants to merge 1 commit intomainfrom
kacpersaw/fix-env-race-condition
Draft

fix(provisioner): make coder_env and coder_script iteration deterministic#22706
kacpersaw wants to merge 1 commit intomainfrom
kacpersaw/fix-env-race-condition

Conversation

@kacpersaw
Copy link
Contributor

Description

Fixes #21885

When multiple coder_env resources define the same key for a single agent, the final environment variable value was non-deterministic because Go maps have random iteration order. The ConvertState function iterated over tfResourcesByLabel (a map) to associate coder_env resources with agents, making the order of ExtraEnvs unpredictable across builds.

Changes

  • Added sortedResourcesByType() helper in resources.go that collects resources of a given type from the label map and sorts them by Terraform address before processing
  • Replaced map iteration for coder_env and coder_script association with sorted iteration, ensuring deterministic ordering
  • Added duplicate-env-keys test case and fixture verifying that when two coder_env resources define the same key, the result is deterministic (sorted by address)

How it works

When duplicate keys exist, the last one by sorted Terraform address wins. For example, coder_env.path_a is processed before coder_env.path_b, so path_b's value will be the final one in ExtraEnvs. Since provisionerdserver.go merges ExtraEnvs into a map (last wins), this produces stable, predictable results.

…stic

When multiple coder_env resources define the same key for a single agent,
the final environment variable value was non-deterministic because Go maps
have random iteration order. The ConvertState function iterated over
tfResourcesByLabel (a map) to associate coder_env resources with agents,
making the order of ExtraEnvs unpredictable across builds.

This change introduces sortedResourcesByType(), which collects resources
of a given type from the label map and sorts them by Terraform address
before processing. This ensures that when duplicate keys exist, the last
one by sorted address deterministically wins.

The same fix is applied to coder_script resources for consistency.

Fixes #21885
@kacpersaw kacpersaw force-pushed the kacpersaw/fix-env-race-condition branch from 7fe9aaf to c9282de Compare March 6, 2026 12:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Race condition when multiple coder_env resources define the same key

1 participant