AWS Builder Center

AI-Assisted Infrastructure as Code Review: Catching Misconfigurations Before They Reach Production

A practical guide to adding an AI review gate to your CI/CD pipeline that catches the infrastructure mistakes static analysis tools miss.

Google cloud certified professional machine learning engineer

Why This Topic

AWS Builder Center content that performs well shares a consistent shape: a real implementation experience, a step by step build, an explained architecture decision, and lessons pulled from an actual pain point, not abstract theory. IaC review content on the platform tends to focus on static analysis tools, cfn-lint, tflint, Checkov, which are excellent at catching known rule violations but structurally cannot catch the class of mistake that comes from context: a security group that's technically valid but far too permissive for what the resource actually does, a Lambda timeout that doesn't match its actual workload, an RDS instance sized inconsistently with the traffic pattern described three files away in the application code.
AI-assisted IaC review fills that specific gap. It doesn't replace static analysis, it adds a layer that reasons about intent and context the way a senior engineer reviewing a pull request would, then reports its findings inside the same CI/CD gate the team already trusts. This sits directly in your niche, DevOps Automation with Python extended into AI-assisted tooling, and the guidelines fit is strong because it's a specific, underserved gap rather than a generic "AI can help DevOps" pitch.



The Problem: Static Rules Catch Syntax, Not Intent

Tools like Checkov and tflint are essential and should stay in the pipeline, they catch missing encryption flags, open security group rules, and hardcoded secrets reliably and cheaply. What they cannot do is reason about whether a configuration makes sense given everything else in the codebase:
  • A security group opened to  0.0.0.0/0  on port 22 fails a static rule instantly. A security group opened to a  /16  CIDR range that's technically "restricted" but far broader than the three services that actually need access passes every static check while still being a real risk
  • An IAM policy with  Action: "*"  fails immediately. An IAM policy with fifteen specific but wildly over scoped permissions, none of which the attached Lambda function's code actually uses, passes cleanly
  • A DynamoDB table provisioned with far more capacity than the traffic patterns in the surrounding application code would ever require passes static analysis entirely, since it's not a security or syntax issue at all, it's a cost and design issue that requires reading the code around it
These are exactly the findings an experienced reviewer catches by reading the change in context, and exactly what static, rule based tools are structurally unable to catch.



The Architecture: A Context-Aware Review Gate

[ Pull Request: Terraform/CloudFormation change ]
|
v
[ Static analysis: Checkov / tflint / cfn-lint ] --(existing, unchanged)
|
v
[ AI Review Stage ]
|
(gathers context: diff, related app code, existing resource tags/naming)
|
v
[ Bedrock: structured review against context, not just syntax ]
|
v
[ Findings posted as PR comments, categorized by severity ]
|
v
[ Human reviewer: confirms, dismisses, or acts on each finding ]
The critical design boundary: the AI review stage is advisory, posted as PR comments, not a merge blocker on its own. Static analysis failures can safely block a merge because they're deterministic and low false-positive. AI-generated findings, even good ones, still need a human in the loop, treating them as a hard gate would either create alert fatigue from false positives or, worse, train the team to blindly trust an AI's judgment on infrastructure changes.



Step 1: Gathering Context Beyond the Raw Diff

The value of this approach depends entirely on giving the model more than just the changed lines. Pulling in the surrounding resource definitions and any directly related application code is what makes the review contextual rather than generic:
python
import subprocess
from pathlib import Path

def get_pr_diff(base_branch="main"):
result = subprocess.run(
["git", "diff", f"{base_branch}...HEAD", "--", "*.tf", "*.yaml", "*.yml"],
capture_output=True, text=True, check=True,
)
return result.stdout

def get_full_resource_context(diff_text, terraform_dir="infra/"):
"""Extracts resource names touched in the diff, then pulls their
full current definitions, not just the changed lines, so the
model sees complete resource blocks rather than fragments."""
changed_files = {
line.split(" b/")[-1]
for line in diff_text.splitlines()
if line.startswith("+++") and "b/" in line
}

full_context = {}
for file_path in changed_files:
path = Path(file_path)
if path.exists():
full_context[file_path] = path.read_text()

return full_context

def find_related_application_code(resource_names, app_dir="src/"):
"""Greps for references to changed resource names in application
code, e.g. a Lambda function name referenced in its own handler,
to give the model a sense of actual usage, not just declared config."""
matches = {}
for name in resource_names:
result = subprocess.run(
["grep", "-rl", name, app_dir],
capture_output=True, text=True,
)
if result.stdout.strip():
matches[name] = result.stdout.strip().splitlines()
return matches
This step is the difference between "AI reviews a diff" and "AI reviews a diff with the same context a human reviewer would gather before commenting."



Step 2: Structured Review Against Context

The prompt design here matters more than the model choice. Asking for structured, categorized findings, rather than freeform commentary, is what makes the output usable inside a PR comment rather than a wall of text nobody reads:
python
import boto3
import json

bedrock = boto3.client("bedrock-runtime", region_name="us-east-1")

def review_infrastructure_change(diff_text, resource_context, related_app_code):
context_block = "\n\n".join(
f"--- {path} ---\n{content[:3000]}" for path, content in resource_context.items()
)
app_usage_block = "\n".join(
f"{name} referenced in: {', '.join(files[:3])}" for name, files in related_app_code.items()
) or "No related application code found."

prompt = f"""Review this infrastructure change as a senior DevOps engineer would in a
pull request review. You have the full diff, the complete resource definitions, and
where relevant resources are referenced in application code.

DIFF:
{diff_text[:4000]}

FULL RESOURCE CONTEXT:
{context_block}

APPLICATION CODE USAGE:
{app_usage_block}

Focus specifically on issues that require understanding intent and context, not
things a static linter would already catch (missing encryption, open CIDR ranges,
hardcoded secrets). Look for: overly broad permissions relative to actual usage,
resource sizing inconsistent with apparent traffic patterns, naming or tagging
inconsistencies with the rest of the codebase, and configuration that seems
disconnected from how the resource is actually used in application code.

Respond as JSON, a list of findings, each with:
{{"severity": "high|medium|low", "resource": "...", "finding": "...", "suggestion": "..."}}
If there are no context-dependent issues, return an empty list."""

response = bedrock.invoke_model(
modelId="anthropic.claude-3-5-sonnet-20241022-v2:0",
body=json.dumps({
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 1200,
"messages": [{"role": "user", "content": prompt}],
}),
)
result = json.loads(response["body"].read())
return json.loads(result["content"][0]["text"])
The explicit instruction to skip what static linters already catch is deliberate. Without it, the model spends its output budget restating findings Checkov already reported, which duplicates existing signal instead of adding new signal.



Step 3: Posting Findings as PR Comments

Findings are only useful where the reviewer is already looking, inline on the pull request, categorized so high severity items aren't buried among low severity style notes:
python
import requests
import os

GITHUB_TOKEN = os.environ["GITHUB_TOKEN"]
REPO = os.environ["GITHUB_REPOSITORY"]
PR_NUMBER = os.environ["PR_NUMBER"]

def post_findings_as_comment(findings):
if not findings:
return

severity_order = {"high": 0, "medium": 1, "low": 2}
findings_sorted = sorted(findings, key=lambda f: severity_order.get(f["severity"], 3))

body_lines = ["## AI Infrastructure Review\n", "_Context-aware findings, in addition to standard static analysis:_\n"]
for f in findings_sorted:
icon = {"high": "🔴", "medium": "🟡", "low": "🔵"}.get(f["severity"], "⚪")
body_lines.append(f"{icon} **{f['severity'].upper()}** — `{f['resource']}`\n{f['finding']}\n> Suggestion: {f['suggestion']}\n")

response = requests.post(
f"https://api.github.com/repos/{REPO}/issues/{PR_NUMBER}/comments",
headers={"Authorization": f"token {GITHUB_TOKEN}"},
json={"body": "\n".join(body_lines)},
)
response.raise_for_status()



Real World Scenario: What This Catches

A pull request adds a new Lambda function with an attached IAM role granting  s3:*  on a specific bucket, which passes static analysis cleanly since the resource ARN is scoped correctly. The AI review stage, given the related application code showing the Lambda handler only ever calls  get_object  and never writes or deletes, flags it as a medium severity finding: permissions granted (full S3 access) are broader than actual usage (read-only), with a suggested scoped-down policy. Static analysis had nothing to flag here, since nothing was technically misconfigured, but the finding still represents real, unnecessary blast radius that a context-aware review catches and a rule-based one structurally cannot.



Common Pitfalls

  • Treating AI findings as a merge blocker. Keep this advisory. A false positive blocking a deploy erodes trust in the tool faster than any number of good findings build it.
  • Skipping the "don't duplicate static analysis" instruction. Without it, the model's output is dominated by findings a linter already caught, drowning out the genuinely new, context-dependent signal.
  • Feeding only the diff, not full resource context. A three line diff to a security group rule is meaningless without seeing the full rule set and what it's attached to. Context is the entire value proposition here.
  • Running this on every file type indiscriminately. Scope it to actual infrastructure files (Terraform, CloudFormation, CDK output), running it against application code dilutes both cost and relevance.
  • Not tracking false positive rate over time. Log which findings get dismissed versus acted on, and use that signal to refine the prompt, an AI review tool that's ignored after a few false alarms provides zero value regardless of how it's built.



Closing Thought

Static analysis and AI-assisted review aren't competing approaches, they cover genuinely different failure modes. Static tools are fast, deterministic, and excellent at catching known rule violations, exactly what they should keep doing. AI-assisted review adds the layer that requires reading a change in context, the same thing a thoughtful senior engineer does in a pull request review, at the same point in the pipeline where that judgment is already trusted. The result isn't a replacement for human review, it's a way to surface the context-dependent findings a static ruleset can never express as a rule, before they ship instead of after an incident makes them obvious.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article