
Summary
Key points of this document
- As the number of manual synchronization points increases, configuration omissions structurally occur.
- Dividing variables into 3 layers: injection point and secrecy
- Write the variable contract, not the actual value, in the single source.
Overview
In a business infrastructure with an increasing number of services, the same environment variables are duplicated across Docker Compose, configuration examples, Terraform, and application code, making it easy for synchronization omissions to occur with every addition or change. This article organizes a design that narrows down human-editable declarations to service-specific manifests, generates validation schemas and settings for local execution, and stops discrepancies with CI. The completed foundation and migration tasks requiring validation in the actual environment are treated separately.
As the number of manual synchronization points increases, configuration omissions structurally occur.
In small configurations, individually maintaining Docker Compose's environment, developer-oriented configuration examples, Terraform's variables and connections to execution environments, and process.env references within applications does not impose a significant burden. However, as the number of services and integrations increases, adding a single variable requires updating multiple locations with the same content. Even if only one location is outdated, it is difficult to find during review and leads to different failures depending on the execution environment.
What's more troublesome is a configuration that doesn't check for the existence of variables until the code actually uses them. Even if database connection or external API credentials are missing, the process will still start, only to fail for the first time with the initial request or periodic processing. The success of deployment does not equate to the application being able to operate.
The core of the solution is not to gather all configuration values into one giant file. It is to declare the name and nature of the variables each service needs in one place, and generate downstream formats. This creates a state where people do not write the same information multiple times, and changes that do not go through generation are detected by CI.
Dividing variables into 3 layers: injection point and secrecy
Before single-sourcing, environment variables are divided into three layers. The first is public settings embedded during frontend builds. Values with the Vite VITE_ prefix, for example, can be read from deliverables, so credentials cannot be placed there. The second is non-secret settings passed at runtime. This includes execution modes, public connection destinations, and bucket names. The third is runtime secrets such as database connection information, signing keys, and external API keys.
This classification determines the storage location and validation method. Build-time public settings are treated as inputs to the build graph, and runtime non-secret settings are passed from Terraform or Docker Compose. Runtime secrets are injected from Secret Manager into execution environments like Cloud Run, and actual values are not left in the repository.
If you try to handle all three layers with a single mechanism, the boundary between public and secret values becomes ambiguous. Build-time settings already managed by other primary sources should not be redundantly incorporated, and this manifest will limit its scope to runtime non-secret settings and secret metadata. A single source is not better just because it's wider; it's important to consolidate within a scope where responsibilities do not overlap.
- build-time: Public settings embedded in deliverables. No secrets should be placed here.
- runtime (non-secret): Execution modes and public connection destinations. Injected from Terraform or Docker Compose.
- runtime (secret): Connection information and signing keys. Actual values are injected at runtime from Secret Manager, etc.
Write the variable contract, not the actual value, in the single source.
The primary information edited by humans will be service-specific JSON manifests. Each variable will have a name, whether it's a secret, if it's required at startup, the environment it uses, its identifier in the secret store, and a clear dummy value usable during development. Actual secret values are not included in the manifest. Single-sourcing is not about the credentials themselves, but about the contract of how credentials are handled.
Dividing by service is to narrow the scope of change impact. If all service variables are put into one giant JSON, irrelevant diffs will be mixed in with every review, and ownership will become ambiguous. Common variables can be composed by the generator, but what each service needs remains as individual declarations.
When migrating from an existing configuration, you can generate a draft manifest from normalized Docker Compose output and Terraform definitions. However, the process of inferring secrecy from variable names is only used for initial input. Even if a value ends with PASS, it might be judged as secret, even for public IDs or public keys. A division of roles is necessary: the machine creates the draft, and humans verify the injection path and usage code to finalize it.
If not injected, stop startup instead of running with weak default values.
If you place a fixed fallback for values like authentication signing keys to ease development, the system will continue to operate with a known key even if injection fails in production. While monitoring might show it as normal, it could lead to a state where signatures can be forged. In cases of missing credentials, fallbacks prioritizing availability can compromise security.
In production, if essential secrets are missing, an exception should be thrown at startup. If dummy values are allowed for development or testing, they should be clearly identifiable as development-only values, and the code should fix conditions where they cannot be used in strict execution modes. It's also crucial that the system doesn't default to a lenient state when the environment determination flag itself is unset.
Synthesize common schemas and service-specific schemas with zod, and synchronously validate them at the uppermost entry point. If the configuration evaluates modules before listening (e.g., with Bun), an exception here will result in process startup failure. Moving validation before the first request allows detection of configuration deficiencies at the deployment stage.
Even relaxed modes for development should not be lenient by default. They should only be enabled when it's explicitly opted-in, in addition to being for development or testing. Unset, misspelled, or unexpected values should be treated as strict. To prevent inconsistent judgments due to different environments being referenced during schema assembly and value validation, the environment source should be explicitly passed from the schema generation side.
In generated env files, empty values like NAME= might be output to indicate only the injection target for secret values. If z.string().min(1).optional() is used as is, an empty string is not undefined but an "existing invalid value," causing even optional items or items with development default values to fail. Normalize empty strings to undefined before validation, treat optional items as uninjected, and judge required items based on the execution mode.
- Production-essential secrets: if not injected, fail startup.
- Development dummy values: use clearly identifiable names and values, reject in strict mode.
- Empty strings: normalize to uninjected before validation to ensure consistent required/optional rules.
- Optional secrets: explicitly check for uninjected status where actually used.
Generate from declarations, prevent drift with CI checks.
The generator reads the manifest and first creates zod service-specific schemas, a barrel file exposing all schemas, and environment files for Docker Compose. Secret items only output their names, not actual values, into committed generated artifacts. Required status and minimum length are passed to startup validation, while identifiers for usage environments and secret stores are kept in a format transferable to subsequent infrastructure generation.
If generated artifacts are included in the repository, pair generation commands with check commands. The check command temporarily regenerates content and compares it with committed files, displaying a unified diff and failing if there are differences. This detects direct editing of generated artifacts or forgetting to regenerate after manifest changes before review.
The scope of schema ownership is also fixed. Common items like NODE_ENV and PORT are owned only by the common schema and are not redefined in generated service-specific schemas. On the other hand, items with limited usage, like DATABASE_URL, are made mandatory only by the services that require them. The order of synthesizing common schemas, generated schemas, and handwritten additional constraints is also determined to prevent unintended overwrites of keys with the same name.*At the generator's entry point, reject unknown fields, duplicate variable names, strings that look like actual secrets, local values outside their scope of use, and overly weak development dummy values. Orphaned generated files that remain after being deleted from the manifest are also subject to checks. Errors in a single source propagate to all generation targets, so they are stopped at both the input and post-generation sides.*Here, there's no need to switch all downstream systems at once. First, generate startup schemas and local templates. Then, add Terraform wiring and developer configuration examples as consumers, starting with those whose behavioral equivalence can be confirmed. The foundation of a single source and the migration of existing systems to use it are separate completion conditions.
Reconcile declarations and executable code in both directions.
Just having a manifest doesn't cover all environment variables referenced by executable code. Use the list of services to be executed as the canonical source, explicitly stating for each service whether it owns an environment variable, shares it as an alias, or has no runtime configuration. This prevents omissions, such as adding a new service without a manifest.
Reconciling declaration and execution code in both directions
Merely having a manifest does not cover all environment variables referenced by the execution code. Using the list of services to be executed as the canonical source, explicitly define for each service whether it is the owner of an environment variable, shares a relationship as an alias, or has no runtime configuration. This prevents omissions such as adding a new service but lacking a manifest.
Next, we trace the backend and worker entry points from the build catalog and collect environment variable references in the first-party import closure. We use static analysis to match references like process.env against the manifest, failing if undeclared names or dynamic references are detected. This provides stronger validation than a one-way ledger check, as it can find discrepancies whether the implementation changes first or the declaration changes first.
This matching should not be limited to generator tests; we must enforce generation drift checks, manifest coverage tests, and execution code reference checks in CI. Since static analysis alone cannot determine if values are actually injected, it is predicated on being combined with subsequent startup smoke tests.
Furthermore, if CI does not rebuild dependent services when a common env package or manifest is changed, only the declarations in the repository will be new, while the execution images remain old. The mechanism for selecting validation targets from changed files must include dependencies from common env definitions to consuming services. The impact of a single source must propagate not only through generation but also through build and startup verification.
- Explicitly declare either owner, alias, or no configuration required for all services to be executed.
- Collect actual environment variable references from entry points and import closures, and match them against declarations.
- Stop dynamic references and undeclared variables with blocking checks, rather than relying on reviews.
- When common env definitions change, rebuild all consuming services and verify their startup.
Avoid over-specifying 'required' and the spread of shared dependencies.
Introducing fail-fast might tempt one to make all credentials 'required'. However, external integration secrets may only be conditionally injected into services that use that specific feature. Making them universally required could prevent services that currently don't use that feature from starting. Before making something 'required', confirm it's unconditionally injected in all target environments; for ambiguous values, start with a combination of 'optional' and runtime checks.
Where a common validation package is read from also affects the scope of impact. Adding a new package dependency to a deeply shared module in the dependency graph can cause changes to ripple through the Dockerfiles and installation procedures of all services that use that module. It's pointless to increase manual multi-point tasks for the sake of commonality.
Therefore, it becomes easier to handle if the validation package is placed near the application's entry point, and deeply shared modules receive validated values as arguments. If validation is exceptionally needed within a shared module, a small runtime check can be left. This prioritizes not increasing the chain of dependencies over unifying abstraction.
Docker Compose: Gradual migration with normalized configuration diffs.
Docker Compose's 'environment' section can include specifications to inherit host environment variables if they exist, or make them empty otherwise. If you write secret items with empty values to a generated 'envfile' and replace existing 'environment' specifications all at once, you might overwrite values passed from the host with empty ones. Since 'environment', 'envfile', shell, and .env have precedence, equivalence cannot be judged solely by file appearance.
Start the migration with services that do not inherit from the host. Before and after the change, output the normalized service configuration with 'docker compose config' and compare the set and values of environment variables. Only move services where no differences were confirmed to 'env_file', and keep variables inherited from the host in 'environment' for combined use.
This verification cannot be replaced by generator unit tests. The final configuration must be compared, including the actual Docker Compose version, .env, and shell environment in use. Progressing in smaller units where equivalence can be proven, rather than a bulk replacement, makes rollbacks easier if the development environment is broken.
Terraform commonization: Start by preserving resource addresses.
Folding service-specific environment variables and Secret Manager connections into 'map' and 'foreach' in Terraform significantly reduces duplication. However, moving existing resources under a 'module' or 'foreach' changes their resource address. If Terraform cannot recognize them as the same entity, it will plan a deletion and recreation, which risks stopping the execution environment or secret connections.
To retain existing resources, map the addresses before and after the change using a moved block. Then, ensure that terraform plan using the actual state and credentials does not include any changes other than the move. Passing terraform validate confirms syntax but does not guarantee that existing resources will not be recreated.
This task remains incomplete if the state cannot be reached locally. Verify the moved block and plan for each resource or service, proceeding in an order that allows reverting to the previous definition if any anomalies are found. Even if the generator is complete, it is not considered production-ready until an empty plan against the actual state is confirmed.
Validation separates generation consistency from execution environment equivalence.
At the generation layer, we perform JSON Schema validation of manifests, duplicate variable name detection, checking for real-value-like strings in secret items, detection of orphaned generated files, zod tests synthesizing the generation schema, and drift detection via check. We differentiate between strict and relaxed (explicitly opt-in for development), testing for missing mandatory secrets, empty strings, minimum length violations, and unset optional secrets.
At the execution environment layer, we check Docker Compose normalized diffs, container startup smoke tests, injection permissions from Secret Manager, and Terraform plans. Specifically, even if the validation schema is correct, the application cannot start if variables are not passed from the execution environment. Logs that can separately observe where failures occur—declaration, generation, injection, or startup—are also necessary.
Additionally, heuristic and optional specifications for automatic classification are periodically reviewed. Due to feature additions, a secret that was previously optional may become unconditionally required. Single-sourcing is not a one-time migration task but an ongoing operation to continuously inspect whether actual injection paths and declarations match.
- Declaration: Inspect schema, duplicates, and accidental inclusion of real secret values.
- Generation: Inspect regeneration diffs, zod schema, and
strictvs.relaxedbehavior. - Injection: Verify Docker Compose normalized diffs, Secret Manager permissions, and Terraform plan.
- Startup: Start the process with minimal configuration, confirm fail-fast before listening, and health checks when normal.
Decision criteria brought by single-sourcing
What's important in single-sourcing environment variables is not storing all values in the same place. It's about having a single contract edited by humans, keeping actual secret values in an external secret store, and generating formats specific to each consumer. Separating declaration, generation, and injection clarifies what should be written where.
Also, making startup validation too strong can break existing environments. required should be limited to values injected unconditionally, and conditional secrets should undergo additional checks at the time of use. The completion condition for Docker Compose or Terraform migration is not that generation was successful, but that the configurations and plans before and after the change are equivalent.
If you are manually copying the same declaration to multiple places, single-sourcing and a generator are effective. However, maintaining that effectiveness relies on schema contracts (including empty values), reconciliation with actual code, and CI checks that propagate to consuming services. Not manually editing generated artifacts and not considering changes complete until they can be confirmed in a real environment are practical principles for long-term environment variable management.


