Inferensys

Prompt

Infrastructure as Code Review Prompt

A practical prompt playbook for using the Infrastructure as Code Review Prompt in production AI workflows to catch state management issues, drift risks, and security misconfigurations before deployment.
DevOps engineer deploying LLM to production on laptop, Kubernetes dashboards visible, late night deployment session.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the ideal user, required context, and operational boundaries for the Infrastructure as Code Review Prompt.

This prompt is designed for DevOps engineers, platform teams, and cloud architects who need a structured, automated first pass at reviewing Infrastructure as Code (IaC) before it reaches a human reviewer or a CI/CD merge gate. It targets Terraform, Pulumi, and CloudFormation configurations. The primary job-to-be-done is catching architectural and operational risks that static analysis tools like terraform validate or cfn-lint cannot express—such as hardcoded secrets, missing dependency ordering, state management risks, and module reuse violations. Use it when you want a design-level review that reasons about intent, blast radius, and operational fragility, not just syntax errors.

The ideal user provides the full IaC file or module as [INPUT] and optionally a [CONTEXT] block describing the deployment environment, team standards, or known constraints. The prompt works best in a pre-commit hook, a PR review workflow, or a CI pipeline stage where a language model can reason about architectural intent before human review begins. It is not a replacement for terraform plan, pulumi preview, or cfn-lint; those tools should still run and pass before this prompt is invoked. The prompt adds a layer of semantic reasoning on top of syntactically valid code.

Do not use this prompt for real-time production configuration changes, for generating IaC from scratch, or for enforcing compliance with regulatory frameworks that require certified auditors. It is a review assistant, not an approval authority. The output should always be treated as findings for a human to verify, prioritize, and act on. In high-risk environments—such as those managing PII, financial data, or healthcare infrastructure—require human sign-off on every finding before merging. The prompt is most effective when paired with a validation harness that checks the output schema, logs findings for auditability, and blocks merges only when combined with human review gates.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works, where it fails, and the operational prerequisites for using it safely in a production IaC review pipeline.

01

Good Fit: Deterministic Static Analysis

Use when: reviewing Terraform, Pulumi, or CloudFormation for hardcoded secrets, missing dependency ordering, or provider version pinning. The prompt excels at pattern-matching against well-known anti-patterns and configuration smells that have clear, rule-based definitions.

02

Bad Fit: Runtime Drift Detection

Avoid when: you need to compare declared state against live cloud resources. Risk: The model cannot query your AWS, Azure, or GCP APIs and will hallucinate drift analysis. Guardrail: Use this prompt only for static code review; pair it with a drift detection tool like terraform plan or actual state file comparison for runtime validation.

03

Required Input: Complete Module Context

Risk: Reviewing a single .tf file without its variables.tf, outputs.tf, and provider configuration leads to false positives on undefined variables and false negatives on cross-module security gaps. Guardrail: Always bundle the full module or stack directory as input. If using a remote module source, include the module's interface contract.

04

Operational Risk: Secret Exposure in Logs

What to watch: The prompt's output may echo back hardcoded secrets it finds in the input code. Guardrail: Implement a post-processing redaction step in your harness that scans the model's output for high-entropy strings or known secret patterns before the output is logged, stored, or displayed in a UI.

05

Operational Risk: Stale Policy Enforcement

What to watch: The prompt's internal checklist for security best practices (e.g., TLS 1.2 minimum, specific key algorithms) will become outdated. Guardrail: Version your prompt template alongside your compliance policy documents. Schedule a quarterly review to update deprecated ciphers, retired services, and new provider features in the prompt's constraints.

06

Bad Fit: Cost Estimation

Avoid when: you need a precise monthly cost forecast for the defined infrastructure. Risk: The model lacks real-time pricing data and cannot accurately calculate SKU-specific costs, committed use discounts, or data transfer charges. Guardrail: Pipe the IaC plan into a dedicated cost estimation tool (e.g., Infracost) and use this prompt only to flag obviously unbounded or expensive resource configurations.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A ready-to-use prompt for reviewing Infrastructure as Code (IaC) configurations, with placeholders you can adapt for your specific stack and risk profile.

This is the core prompt template for an Infrastructure as Code review. It is designed to be pasted directly into your AI system, with square-bracket placeholders replaced by the actual values for your specific review task. The prompt instructs the model to act as a principal cloud architect and systematically evaluate an IaC configuration against a defined set of criteria, producing a structured, actionable report. The template is self-contained; you can use it without the rest of this playbook, but the surrounding sections will help you integrate it reliably into a production workflow.

code
You are a principal cloud architect reviewing an Infrastructure as Code (IaC) configuration. Your goal is to identify risks, bugs, and deviations from best practices before deployment.

## Review Context
- **IaC Tool:** [IAC_TOOL]
- **Cloud Provider(s):** [CLOUD_PROVIDER]
- **Primary Service(s) Under Review:** [SERVICE_LIST]
- **Risk Profile:** [RISK_LEVEL] (e.g., Low, Medium, High, Critical)

## IaC Configuration to Review
```[IAC_TOOL]
[IAC_CODE_BLOCK]

Review Criteria

Analyze the configuration against the following dimensions. For each finding, provide a severity (CRITICAL, HIGH, MEDIUM, LOW), a clear description, the exact resource and line reference, and a concrete, actionable remediation.

  1. State Management: Check for misconfigured remote backends, missing state locking, or sensitive data in state files.
  2. Drift Risk: Identify resources susceptible to configuration drift due to manual changes or missing lifecycle policies (e.g., prevent_destroy).
  3. Security & Secrets: Flag hardcoded secrets, overly permissive IAM roles/policies, unencrypted data stores, and public exposure of private resources.
  4. Module Reuse & Design: Assess if the code follows the principle of least repetition. Identify monolithic templates that should be refactored into reusable modules.
  5. Plan Determinism: Identify any dynamic or unpredictable values that could cause unexpected changes on the next plan or apply.
  6. Dependency Ordering: Check for missing explicit dependencies (depends_on or equivalent) that could lead to race conditions or creation failures.
  7. Hardcoded Values & Parameterization: Flag any hardcoded names, IDs, AMIs, or regions that should be variables or data source lookups.
  8. Naming & Tagging Convention: Evaluate resource naming and tagging strategy for consistency, sortability, and cost allocation.

Output Schema

Return your findings as a single JSON object matching this exact schema. Do not include any text outside the JSON object. { "summary": "A 2-3 sentence executive summary of the overall configuration quality and top risks.", "findings": [ { "id": "F-001", "severity": "CRITICAL|HIGH|MEDIUM|LOW", "dimension": "The review criterion from the list above.", "resource": "The specific resource address (e.g., aws_s3_bucket.data).", "line_reference": "Approximate line number or block name.", "description": "A clear, specific explanation of the problem.", "remediation": "A concrete, actionable fix." } ], "score": { "overall": "PASS|FAIL|WARN", "security_posture": "PASS|FAIL|WARN", "operational_maturity": "PASS|FAIL|WARN" } }

Constraints

  • Do not hallucinate resource types or provider features.
  • If you are uncertain about a finding, flag it as LOW severity and note the uncertainty.
  • If the configuration is empty or unparseable, return a single CRITICAL finding explaining this.
  • Prioritize findings that could cause an outage, security breach, or data loss.

To adapt this template, replace the placeholders with your specific context. For [IAC_TOOL], use terraform, pulumi-python, cloudformation, etc. The [RISK_LEVEL] input should influence the model's scrutiny; for a production database, you might set it to CRITICAL to encourage a stricter review. The most critical part of the template is the Output Schema. By demanding a strict JSON structure, you can parse the findings programmatically, post them as comments on a pull request, or feed them into a ticketing system. If you are using a model that supports it, you can convert the Output Schema into a JSON Schema for guaranteed structured output via the API.

IMPLEMENTATION TABLE

Prompt Variables

Each variable must be populated before the prompt is sent. Validation notes describe how to programmatically verify the input before execution.

PlaceholderPurposeExampleValidation Notes

[IAC_CODE]

The full Infrastructure as Code source file to review

main.tf containing 200 lines of Terraform HCL

Non-empty string. Must parse as valid HCL, YAML, or JSON depending on tool. Reject if file exceeds 8000 lines or contains binary content.

[IAC_TOOL]

The IaC tool or framework used

terraform

Must match an allowed enum: terraform, pulumi, cloudformation, bicep, ansible, crossplane, cdk8s, null. Reject unknown values.

[PROVIDER]

Cloud provider or platform target

aws

Must match an allowed enum: aws, azure, gcp, kubernetes, helm, null. Required when [IAC_TOOL] is terraform, pulumi, or cloudformation.

[REVIEW_DEPTH]

Level of analysis detail requested

comprehensive

Must match an allowed enum: quick, standard, comprehensive. Controls output verbosity and number of checks performed.

[FOCUS_AREAS]

Specific concerns to prioritize in review

["state_management", "secret_handling"]

Optional JSON array of strings. Allowed values: state_management, drift_risk, module_reuse, secret_handling, plan_determinism, hardcoded_values, dependency_ordering, provider_pinning, null. Reject unknown focus areas.

[MODULE_REGISTRY]

Internal module registry URL or path for reuse checks

Optional string. If provided, must be a valid URL or local path prefix. Used to detect ad-hoc resource definitions that duplicate registered modules.

[COMPLIANCE_STANDARD]

Compliance framework to check against

CIS_AWS_1.5

Optional string. Allowed values: CIS_AWS_1.5, CIS_AZURE_2.0, SOC2, HIPAA, PCI_DSS, null. When set, adds policy-as-code style checks to the review.

[PREVIOUS_PLAN_OUTPUT]

Output from a prior terraform plan or pulumi preview for drift comparison

terraform plan -out=plan.binary output in JSON

Optional string. If provided, must be valid JSON with resource_changes array. Used to detect configuration drift between code and deployed state.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the IaC review prompt into a CI/CD pipeline or pre-commit hook with validation, retries, and human approval gates.

This prompt is designed to operate as a blocking quality gate in a deployment pipeline, not as an advisory chatbot. The primary integration point is a pull request check that runs against terraform plan output, CloudFormation change sets, or Pulumi preview diffs before apply is permitted. The harness must capture the full plan artifact—not just a diff summary—because the prompt requires resource-level detail to detect drift risk, missing dependency ordering, and hardcoded values. Wire the prompt into a GitHub Actions workflow, GitLab CI job, or Jenkins stage that executes after plan generation and before any approval step. The model call should be synchronous within the pipeline; a response time of 15–45 seconds is acceptable for a blocking review, but set a hard timeout of 90 seconds with a fallback to pass with warning to avoid pipeline stalls.

Validation and retry logic is critical because the output schema is strict JSON with enumerated severity levels (BLOCKER, CRITICAL, WARNING, INFO). After receiving the model response, run a JSON schema validator against the expected structure: an array of finding objects, each with id, severity, resource_address, title, description, remediation, and rule_id fields. If parsing fails or required fields are missing, retry once with the same input plus the validation error message appended as a [REPAIR_INSTRUCTION]. If the second attempt also fails, fail the pipeline check open with a diagnostic log—never block a deployment on an unparseable model output. For high-risk environments, add a post-processing step that cross-references each BLOCKER finding against a human approval queue: if any blocker references aws_iam_role, aws_kms_key, or google_project_iam_member, route the finding to a designated security reviewer before the pipeline can proceed.

Model choice and tool use should favor models with strong structured output support and long context windows. Use gpt-4o or claude-3-5-sonnet with the response_format parameter set to json_object and the system prompt instructing strict schema adherence. The plan artifact can exceed 20,000 tokens for large infrastructures; if the plan exceeds the model's context window, preprocess it by extracting only create, update, and delete actions, stripping unchanged resource blocks, and summarizing repetitive resource arrays. Do not use RAG for this workflow—the plan is the single source of truth and must be reviewed in full. If the IaC tool supports machine-readable plan output (e.g., Terraform's JSON plan format), prefer that over human-readable text to reduce token waste on formatting characters. Log the full prompt, response, and validation result to your observability platform with trace IDs that link back to the specific commit SHA and plan artifact version.

Failure modes to instrument: the most common production failures are (1) plan artifacts exceeding context windows, causing truncated reviews that miss resources at the end; (2) the model hallucinating resource addresses that don't exist in the plan, producing false positives that erode trust; (3) severity inflation where every finding is marked BLOCKER, causing pipeline fatigue and manual override habits; and (4) secret detection false negatives where hardcoded values in locals blocks or variable defaults are missed because the model only scans resource arguments. Mitigate these by adding a pre-flight context-length check that fails the pipeline if the plan exceeds 80% of the model's context window, a post-processing deduplication step that removes findings referencing nonexistent resource addresses, a severity distribution monitor that alerts if BLOCKER findings exceed 30% of total findings, and a complementary static analysis tool (e.g., tfsec, checkov) that runs alongside the LLM review to catch deterministic secret and policy violations the model might miss.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, types, and validation rules for the structured JSON response returned by the IaC review prompt. Use this contract to parse, validate, and route findings in your application harness.

Field or ElementType or FormatRequiredValidation Rule

review_id

string (UUID v4)

Must match regex for UUID v4. Generate if absent.

findings

array of objects

Must be an array. If no issues, return an empty array.

findings[].severity

enum: CRITICAL, HIGH, MEDIUM, LOW, INFO

Must be one of the listed enum values. Case-sensitive.

findings[].category

enum: state_management, drift_risk, module_reuse, secret_handling, plan_determinism, hardcoded_value, dependency_ordering, other

Must be one of the listed enum values. Use 'other' only if no category fits.

findings[].resource_address

string

Must be a non-empty string referencing the specific Terraform/Pulumi/CloudFormation resource path.

findings[].description

string

Must be a non-empty string between 20 and 500 characters.

findings[].remediation

string

Must be a non-empty string between 20 and 1000 characters.

summary

object

Must contain total_resources_analyzed and total_findings as integers.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when using AI for IaC review and how to prevent it in production.

01

Hallucinated Resource Dependencies

What to watch: The model invents dependency relationships between resources that don't exist in the code, leading to incorrect ordering or drift risk assessments. Guardrail: Require the model to cite specific resource blocks and depends_on or references lines for every dependency claim. If no explicit dependency exists, flag it as a potential implicit dependency for human review.

02

Stale Provider Knowledge

What to watch: The model applies deprecated provider syntax, removed attributes, or outdated best practices from its training data, generating false-positive findings. Guardrail: Include the provider version and a changelog snippet in the prompt context. Add a validation step that checks findings against the current provider schema before surfacing them.

03

Context Window Truncation

What to watch: Large IaC codebases exceed the context window, causing the model to review only a partial configuration and miss cross-module issues like inconsistent naming or conflicting security groups. Guardrail: Chunk the review by module or service boundary. Run a separate cross-module consistency check with a summary of each module's outputs and variables rather than the full code.

04

Over-Confident Security Findings

What to watch: The model flags a resource as insecure without understanding compensating controls elsewhere in the architecture, generating noise that desensitizes the team. Guardrail: Instruct the model to check for compensating controls before finalizing a severity rating. Require findings to include a 'Verify with' field pointing to the specific security group, IAM policy, or network ACL that should be manually confirmed.

05

Plan Non-Determinism Misdiagnosis

What to watch: The model misidentifies a dynamic value or for_each loop as a plan non-determinism risk when the expression is actually stable, or misses true non-determinism from unconstrained timestamp() or uuid() calls. Guardrail: Add a pre-processing step that extracts all function calls and known non-deterministic patterns. Provide this list to the model and ask it to classify each one as stable or unstable with a one-line justification.

06

Secret Exposure False Negatives

What to watch: The model fails to detect hardcoded secrets when they are passed through variables, locals, or data sources in non-obvious ways, creating a false sense of security. Guardrail: Run a deterministic secret scanner before the AI review. Feed the scanner results into the prompt as ground truth and instruct the model to explain the propagation path for any flagged value, rather than relying on the model to discover secrets from scratch.

IMPLEMENTATION TABLE

Evaluation Rubric

Run these checks against a golden dataset of IaC files with known issues to validate the prompt's output quality before shipping.

CriterionPass StandardFailure SignalTest Method

Hardcoded Value Detection

All hardcoded values flagged with severity and suggested variable replacement

Misses a hardcoded CIDR, AMI ID, or secret string present in the golden file

Parse output JSON for finding_type: hardcoded_value and compare count against known set

State Drift Risk Identification

Flags resources lacking lifecycle prevent_destroy or with mutable unique identifiers

Fails to flag a resource with a mutable name property that forces recreation

Check output for risk: state_drift on the specific resource block in the golden file

Secret Handling Violation

Identifies secrets in plaintext, missing sensitive variable flags, or unencrypted state

Does not flag a password or api_key attribute without sensitive = true

Assert severity: critical exists for the known secret violation in the golden file

Missing Dependency Ordering

Detects implicit dependencies that should be explicit via depends_on

Misses a resource referencing another resource's output without an explicit dependency

Verify output contains a finding for the specific resource pair with risk: race_condition

Module Reuse Opportunity

Suggests module extraction for repeated resource patterns with similar configuration

Does not suggest a module when 3+ nearly identical resource blocks exist

Check for recommendation_type: module_extraction and verify the suggested resource group

Plan Determinism Warning

Flags timestamp(), uuid(), or other non-deterministic functions in resource configs

Misses a timestamp() call inside a resource name or tag attribute

Search output for finding_type: non_deterministic_function and match against known locations

Provider Version Constraint

Identifies missing or overly permissive provider version constraints

Does not flag a provider block with no version constraint or >= only range

Assert output contains finding_type: missing_version_constraint for the provider block

Output Contract Completeness

All findings include resource_path, severity, finding_type, and recommendation

A finding object is missing the resource_path field or has an empty recommendation string

Validate each object in the findings array against the required JSON schema

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add a strict JSON output schema, severity classification, and line-number references. Include retry logic for malformed outputs and log every review result. Wire the prompt into a CI pipeline with blocking gates for CRITICAL findings.

code
Output a JSON object with this schema:
{
  "findings": [
    {
      "severity": "CRITICAL|HIGH|MEDIUM|LOW",
      "category": "SECURITY|DRIFT|STATE|DEPENDENCY|HARDCODED",
      "resource": "[RESOURCE_PATH]",
      "line": [LINE_NUMBER],
      "description": "[FINDING]",
      "remediation": "[FIX]"
    }
  ],
  "summary": "[OVERALL_ASSESSMENT]"
}

Watch for

  • Silent format drift breaking downstream parsers
  • Findings without actionable remediation steps
  • Missing human review gate for CRITICAL security findings
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.