Inferensys

Prompt

Environment Variable Extraction from Source Code Prompt

A practical prompt playbook for using the Environment Variable Extraction from Source Code Prompt in production AI workflows. Designed for DevOps and platform engineers who need to generate a structured, auditable catalog of environment variables directly from a codebase.
Elegant overhead shot of a polished wooden communal table in a sun-drenched WeWork lounge, laptops and tablets displaying AI workflow dashboards, plants and pendant lights in background.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for extracting environment variables from source code into a machine-readable catalog.

This prompt is for DevOps engineers, platform teams, and SREs who need to audit a codebase and produce a machine-readable catalog of every environment variable reference. Use it when you are onboarding to a new service, preparing for a security audit, or generating configuration documentation that must stay synchronized with the actual code. The primary job-to-be-done is converting scattered process.env, os.getenv, System.getenv, or equivalent calls across multiple files into a single structured inventory that includes the variable name, file location, default value, and usage context.

The prompt assumes you can provide representative source files or code snippets. It is not a replacement for a static analysis tool but a fast, flexible way to bootstrap documentation and detect drift. You should use this prompt when you need a human-readable starting point for a configuration audit, when you suspect undocumented environment variables exist in a service you inherited, or when you are preparing a compliance artifact that requires listing every external configuration dependency. Do not use this prompt when you need guaranteed completeness for a safety-critical system—static analysis tools with AST parsing are more reliable for exhaustive extraction. Do not use it when the codebase contains obfuscated, dynamically constructed, or reflection-based variable access that a text-based LLM cannot trace.

Before running this prompt, gather representative source files that contain environment variable access patterns. If the codebase is large, sample the most configuration-heavy modules: database connectors, API clients, authentication middleware, and startup scripts. Provide enough context so the model can distinguish between environment variables and similarly named local variables or constants. After receiving the output, validate it against a known subset of variables you already expect to find. Flag any variable that appears in the catalog but not in your existing documentation as a candidate for investigation. The next section provides the exact prompt template you can adapt and run.

PRACTICAL GUARDRAILS

Use Case Fit

Where the environment variable extraction prompt works reliably and where it introduces risk. Use these cards to decide whether to proceed with a prompt-based approach or invest in a static analysis tool.

01

Good Fit: Polyglot Codebases

Use when: you need a single extraction pass across Python, Node.js, Go, and Terraform files without writing language-specific parsers. Guardrail: include a file-extension filter in the prompt and require the model to tag each variable with its source language so reviewers can spot cross-language false positives.

02

Bad Fit: Obfuscated or Dynamic Access

Avoid when: variables are constructed at runtime through string concatenation, indirect lookup, or encrypted secrets management. Guardrail: add a pre-scan step that flags dynamic access patterns and routes those files to manual review instead of relying on the prompt to resolve them.

03

Required Input: Source Tree with .env Files

Use when: you can provide both the source code and any .env.example, .env, or config schema files as context. Guardrail: the prompt must cross-reference extracted variables against declared defaults and flag any variable found in code but missing from the provided config files as potentially undocumented.

04

Operational Risk: Stale Reference Drift

Risk: the prompt extracts variables correctly at one point in time, but the codebase evolves and the generated reference becomes stale. Guardrail: embed the extraction prompt in a CI pipeline that runs on every merge to main, diffs the output against the previous version, and fails the build if undocumented variables appear or documented variables disappear.

05

Operational Risk: Secret Exposure in Output

Risk: the prompt may extract variable names that imply sensitive values and inadvertently suggest example values that look like real credentials. Guardrail: add a post-processing validation step that scans the generated reference for patterns matching API keys, tokens, or connection strings and redacts or quarantines those entries before publication.

06

Good Fit: Onboarding and Runbook Generation

Use when: new team members need a quick-reference catalog of every environment variable they must set to run the service locally. Guardrail: combine the extraction prompt with a second prompt that groups variables by startup requirement and generates a copy-pasteable .env template with commented descriptions and safe placeholder values.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt that extracts environment variable references from source code into a structured catalog with file location, default value, and usage context.

This prompt template scans source files for environment variable references and produces a structured catalog suitable for documentation, auditing, or drift detection. It handles common access patterns across languages—process.env, os.getenv, os.environ, System.getenv, env.—and distinguishes between direct reads, defaulted reads, and conditional checks. The output is designed to feed directly into a configuration reference pipeline or a variable audit harness.

text
You are an environment variable extraction engine. Your task is to scan the provided source code files and produce a structured JSON catalog of every environment variable reference.

## INPUT
Source files with file paths and content:
[SOURCE_FILES]

## OUTPUT_SCHEMA
Return a JSON object with a single key "variables" containing an array of objects. Each object must have these fields:
- "name": string (the exact environment variable name as referenced in code)
- "file": string (relative file path where the reference appears)
- "line": number (approximate line number, or null if unavailable)
- "access_pattern": string (one of: "direct_read", "defaulted_read", "conditional_check", "boolean_flag", "coerced_read")
- "default_value": string or null (the fallback value if provided, otherwise null)
- "type_hint": string or null (inferred type from coercion or usage: "string", "number", "boolean", "list", "json", or null)
- "required": boolean (true if no default is provided and no conditional guard exists before use)
- "usage_context": string (one-sentence description of how the variable is used at this location)
- "sensitive": boolean (true if the variable name suggests secrets: contains KEY, SECRET, TOKEN, PASSWORD, CREDENTIAL, or is used in auth context)

## CONSTRAINTS
- Include every distinct variable-file combination. If the same variable appears in multiple files, create one entry per file.
- Do not invent variables not present in the source.
- If a variable is read inside a conditional block that checks for its existence first, mark required as false.
- For access patterns: use "direct_read" for bare reads like `process.env.X`; "defaulted_read" for reads with a fallback like `process.env.X || 'default'`; "conditional_check" for `if (process.env.X)` guards; "boolean_flag" for truthiness checks used as feature flags; "coerced_read" for parseInt/JSON.parse wrapping.
- If you cannot determine a field value, use null. Do not guess.
- Sort the output array alphabetically by name, then by file path.

## EXAMPLES
Input:
```javascript
// config.js
const PORT = process.env.PORT || '3000';
const DB_URL = process.env.DATABASE_URL;
if (process.env.ENABLE_FEATURE_X) { ... }

Output:

json
{
  "variables": [
    {
      "name": "DATABASE_URL",
      "file": "config.js",
      "line": 3,
      "access_pattern": "direct_read",
      "default_value": null,
      "type_hint": "string",
      "required": true,
      "usage_context": "Database connection string used to establish backend connectivity",
      "sensitive": true
    },
    {
      "name": "ENABLE_FEATURE_X",
      "file": "config.js",
      "line": 4,
      "access_pattern": "boolean_flag",
      "default_value": null,
      "type_hint": "boolean",
      "required": false,
      "usage_context": "Feature flag controlling experimental feature X activation",
      "sensitive": false
    },
    {
      "name": "PORT",
      "file": "config.js",
      "line": 2,
      "access_pattern": "defaulted_read",
      "default_value": "3000",
      "type_hint": "number",
      "required": false,
      "usage_context": "Network port the server binds to for incoming HTTP requests",
      "sensitive": false
    }
  ]
}

RISK_LEVEL

Low. Output is derived from static analysis of provided source files. No destructive actions. Human review recommended before publishing as documentation.

Now process the provided source files and return only the JSON output with no additional commentary.

To adapt this template, replace [SOURCE_FILES] with your actual source content—typically a concatenation of file paths and their contents, formatted as ### FILE: path/to/file.ext followed by the code block. For large codebases, run the prompt per directory or module to stay within context limits, then merge the results. If your codebase uses custom config wrappers or indirect variable access (e.g., a getConfig('key') helper), add an example of that pattern to the [EXAMPLES] section so the model recognizes it. The sensitive field uses a heuristic based on variable naming—adjust the keyword list in [CONSTRAINTS] to match your organization's secret naming conventions.

Before wiring this into a documentation pipeline, validate the output against a known-good reference. Common failure modes include: missing variables accessed through dynamic string construction (e.g., process.env['PREFIX_' + name]), false positives from commented-out code, and incorrect required classification when guard clauses span multiple files. Run the prompt against a small, well-understood module first and compare the extracted catalog to your manual inventory. If the type_hint field matters for downstream tooling, add a post-processing step that cross-references against a schema registry or config validation layer rather than relying solely on the model's inference.

IMPLEMENTATION TABLE

Prompt Variables

Placeholders required by the environment variable extraction prompt. Replace each with concrete values before sending the prompt. Validation notes describe how to confirm the input is well-formed.

PlaceholderPurposeExampleValidation Notes

[SOURCE_CODE]

The codebase directory, file glob, or pasted source content to scan for environment variable references

src/**/*.ts or paste of server.js

Must be non-empty. For file globs, confirm at least one file matches before prompt execution. For pasted content, enforce a minimum of 10 lines to avoid trivial scans.

[LANGUAGE]

The primary programming language or framework convention used in the source code

Python, TypeScript, Go, Rust

Must match one of the supported language identifiers. Use a controlled vocabulary list. If the language is ambiguous, require explicit specification rather than auto-detection.

[ACCESS_PATTERNS]

A list of known access patterns for environment variables in the target language

process.env.VAR, os.getenv('VAR'), env::var('VAR')

Provide at least one pattern. Validate that each pattern is syntactically valid for the target language. Missing patterns cause false negatives in extraction.

[EXCLUDE_PATTERNS]

File paths, variable names, or comment markers to exclude from the scan

node_modules/, test/, # nosec, SKIP_ENV_CHECK

Can be null or empty. If provided, each pattern must be a valid regex or glob. Test exclusion patterns against a known noisy file to confirm they suppress false positives.

[OUTPUT_SCHEMA]

The exact JSON schema or table format the extracted variables must conform to

JSON array with name, file, line, default, required, type, usage_context fields

Must be a valid JSON Schema or explicit field list. Validate that required fields are present and that the schema includes a field for source location to enable traceability.

[KNOWN_DEFAULTS]

A dictionary of variable names to their documented default values for cross-referencing

{"PORT": "3000", "LOG_LEVEL": "info"}

Can be null. If provided, must be a flat key-value map. The prompt will flag any extracted variable whose default differs from the known default for human review.

[SENSITIVE_KEYWORDS]

A list of substrings that indicate a variable likely contains a secret or sensitive value

KEY, SECRET, TOKEN, PASSWORD, PRIVATE_KEY

Can be null. If provided, use case-insensitive matching. The prompt will add a sensitive: true flag to any variable name matching a keyword. Review keyword list for false positives like ACCESS_KEY_ID which may be non-secret.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the environment variable extraction prompt into a CI/CD pipeline or local audit script with validation, diffing, and human review gates.

This prompt is designed to be called programmatically from a script, Makefile target, or CI/CD pipeline step rather than run interactively. The core workflow is: gather source files, assemble the prompt, call the LLM, validate the response, and store the result as a build artifact. A typical invocation script first collects all files matching a pattern (*.py, *.js, *.go, *.ts) and concatenates them with file path headers so the model can attribute each variable reference to its source location. The concatenated source block is injected into the [SOURCE_CODE] placeholder. If your codebase exceeds the model's context window, split by directory or service and run the prompt multiple times, then merge the resulting JSON arrays.

When calling the LLM, set response_format to json_object (OpenAI) or use the equivalent structured output mode for your model provider to guarantee valid JSON. After receiving the response, validate the JSON against the output contract before accepting it. The expected schema is an array of objects, each containing variable_name (string), file_path (string), line_number (number), default_value (string or null), is_required (boolean), usage_context (string), and sensitive_classification (string enum: secret, sensitive, public). Reject any response missing required fields or containing malformed entries. If validation fails, retry once with a repair prompt that includes the validation error message and the original response. If the second attempt also fails, fail the pipeline step and alert a human.

Store the validated JSON as a build artifact (e.g., env-vars-audit.json) committed to the repository or uploaded to your artifact store. For ongoing audits, diff the generated JSON against the previous run's artifact to detect newly added variables, removed variables, or changed defaults. Flag any variable where is_required changed from false to true for immediate human review, as this may indicate a breaking deployment change. Variables classified as secret should trigger a secondary check: scan the source file to confirm the value is not hardcoded. If a hardcoded secret is detected, block the pipeline and escalate.

Do not run this prompt on files containing hardcoded secrets without first redacting them. Use a pre-processing step (e.g., detect-secrets, trufflehog, or a regex-based scrubber) to mask known secret patterns before the source code reaches the LLM. The model should see REDACTED in place of actual credentials. This prevents accidental exfiltration and keeps secrets out of LLM provider logs. For high-security environments, consider running this prompt against a local model or a private deployment where data never leaves your network boundary.

IMPLEMENTATION TABLE

Expected Output Contract

Validate every extracted environment variable against this contract before ingesting into your config catalog or docs pipeline. Each field maps to a key in the generated JSON object.

Field or ElementType or FormatRequiredValidation Rule

variable_name

string

Must match pattern ^[A-Z_][A-Z0-9_]*$. Reject lowercase or hyphenated names. Must be the exact name used in code.

file_path

string

Must be a relative path from repo root. Validate file exists in the scanned tree. Reject absolute paths or URLs.

line_number

integer

If present, must be >= 1. Null allowed when variable is referenced in config or CI but not in source.

default_value

string | null

Null when no default is provided in code. When present, must be the literal string from the source, not an inferred or transformed value.

usage_context

string

Must be one of: 'assignment', 'conditional_check', 'string_interpolation', 'command_argument', 'config_reference'. Reject unknown context types.

is_secret

boolean

Set true if variable name contains SECRET, TOKEN, KEY, PASSWORD, or CREDENTIAL. Set false otherwise. Manual override allowed with audit log.

referencing_function

string | null

If extraction source is a function body, include function name. Null for top-level or config file references. Must match valid identifier pattern.

extraction_confidence

number

Float between 0.0 and 1.0. Score below 0.7 triggers human review. Score 1.0 only for direct os.getenv or process.env reads with literal string argument.

PRACTICAL GUARDRAILS

Common Failure Modes

When extracting environment variables from source code, these failures surface first in production. Each card identifies a specific breakage pattern and the guardrail that prevents it.

01

Undocumented Required Variables

What to watch: The prompt extracts variables that are referenced in code but never documented in .env.example or config schemas. These become runtime crashes when the variable is missing. Guardrail: Cross-reference extracted variables against existing documentation files. Flag any variable found in code but absent from docs as a critical gap requiring immediate documentation.

02

Stale References to Removed Variables

What to watch: The prompt catalogs variables that appear in documentation or config templates but are no longer referenced anywhere in the source code. These mislead operators into setting dead values. Guardrail: Run a reverse lookup for every documented variable against the codebase. Any variable with zero code references should be flagged for deprecation or removal from docs.

03

Incorrect Default Value Extraction

What to watch: The prompt misreads fallback logic such as process.env.PORT || 3000 and reports the wrong default, or misses conditional defaults based on environment. Guardrail: Require the prompt to cite the exact file and line number for every default value claim. Run a secondary validation pass that parses the same line with a deterministic regex and compares results.

04

Secret Variables Exposed in Output

What to watch: The prompt extracts variable names that are clearly secrets (API keys, tokens, passwords) and includes them in plain-text documentation without sensitivity labels. Guardrail: Apply a naming heuristic before generation—any variable matching patterns like *_KEY, *_SECRET, *_TOKEN, *_PASSWORD must be automatically classified as sensitive and flagged for vault storage, never printed with example values.

05

Environment-Specific Drift Not Detected

What to watch: The prompt treats a variable as having a single definition, but the codebase uses different defaults or required status across dev, staging, and production. Guardrail: Instruct the prompt to group variable references by environment context when conditional logic is detected. Output a per-environment matrix rather than a single flat catalog. Flag any variable with conflicting defaults across environments.

06

Dynamic Variable Construction Missed

What to watch: The prompt misses variables constructed at runtime through string interpolation, prefix patterns, or service-discovery lookups, producing an incomplete catalog. Guardrail: Supplement static extraction with a pattern-matching pass for dynamic construction patterns like template literals, envPrefix concatenation, and config key builders. Report these separately with a confidence note indicating they require manual verification.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the quality of the extracted environment variable catalog before integrating it into your documentation pipeline or CI/CD checks. Each criterion targets a specific failure mode common in code-to-documentation extraction.

CriterionPass StandardFailure SignalTest Method

Variable Completeness

All process.env, os.Getenv, or equivalent references in the target source files are captured in the output.

Output is missing a variable that appears in the source code. Count of extracted vars is less than known references.

Run a regex scan (grep -rE 'process\.env\.|os\.Getenv') on the source directory and compare the unique variable names against the output list.

Default Value Accuracy

The default_value field matches the fallback in the source code exactly, or is null if no default is provided.

Extracted default value is "localhost" but source code shows process.env.DB_HOST || '0.0.0.0'.

Parse the source code's coalescing/nullish operators. For each variable with a default, assert the extracted value matches the right-hand side of || or ??.

File Path Precision

The file_path field contains the correct relative path from the repository root for every reference.

A variable used in src/config/database.ts is attributed to src/config/server.ts.

For a random sample of 5 variables, manually verify the file path in the output against a grep result in the codebase.

Required vs. Optional Classification

Variables without a default value are classified as required: true. Variables with a default are required: false.

A variable with no fallback is marked required: false, which would cause a runtime crash if missing.

Write a script to cross-reference the default_value field. Assert required is true when default_value is null, and false otherwise.

Usage Context Validity

The usage_context field contains a concise, accurate description of how the variable is used, derived from surrounding code.

The context says 'Sets the port' but the variable is actually used as a connection string in a database client.

For 3 variables, provide the source code snippet and the extracted context to an LLM judge. Ask: 'Does the context accurately summarize the code's use of this variable?' Require a score of 4/5 or higher.

No Hallucinated Variables

The output contains zero variables that do not exist in the source code.

The output includes JWT_SECRET but a codebase search returns no results for this string.

Perform an exact string match of every variable name in the output against the source code. Any variable with zero matches is a failure.

Schema Adherence

The output is valid JSON that strictly conforms to the defined [OUTPUT_SCHEMA] with all required fields present.

The output is missing the required field for a variable, or contains an extra key like severity.

Validate the raw model output against the expected JSON Schema using a programmatic validator (e.g., ajv). Reject on any schema errors.

Stale Reference Detection

Variables that are referenced in the codebase but never actually read or used are flagged in a warnings array.

A variable is extracted from a file where it is assigned but the value is never used in any logic path.

Use a static analysis tool (like eslint with no-unused-vars) to find unused variables. Cross-reference with the output's warnings field to ensure they are flagged.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single file or small directory. Drop strict output schema requirements and accept a simple Markdown table. Replace [OUTPUT_SCHEMA] with: Return a Markdown table with columns: Variable Name, File, Line, Default Value, Usage Context.

Watch for

  • False positives from comment references or string literals that look like env vars
  • Missing process.env variants in JavaScript or os.getenv in Python
  • Overly broad extraction that picks up non-environment constants
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.