Infrastructure as Code fails quietly: an open security group, a missing tag, an Ansible task that is not idempotent — small mistakes that pass syntax checks and explode in production. Human reviewers miss them because IaC diffs are long and boring. AI code review is a perfect second pair of eyes: it reads every Terraform plan and every playbook change, and flags risky patterns before they merge. This guide shows you how to add AI code review for Terraform and Ansible to a GitHub Actions pipeline.
What AI Code Review Catches in IaC – AI Code Review for Terraform and
An LLM reviewer is not a replacement for terraform validate or policy tools like Checkov — it complements them by reasoning about intent:
- Security groups open to
0.0.0.0/0on sensitive ports, explained in context. - Resources that will be destroyed and recreated hidden inside a long plan.
- Ansible tasks using
shellwhere a module exists, or missingchanged_whenguards. - Hard-coded secrets, missing tags, unencrypted storage, overly broad IAM policies.
- Changes whose blast radius does not match the pull request description.
The output is a pull request comment your team reads in two minutes — that is the entire point of AI code review in CI.
Prerequisites – AI Code Review for Terraform and
- A GitHub repository containing Terraform and/or Ansible code.
- GitHub Actions enabled, with Terraform CLI available in the workflow.
- An LLM API key stored as a GitHub Actions secret named
LLM_API_KEY. - Familiarity with pull requests and basic CI (see our GitHub Actions CI/CD guide).
Step 1: Generate a Readable Diff for the Reviewer
Models review text, so produce text. For Terraform, the plan in human-readable form works best:
- name: Terraform plan
run: |
terraform init -backend=false
terraform plan -no-color -out=tfplan.binary
terraform show -no-color tfplan.binary > plan.txt
wc -l plan.txt
For Ansible, the pull request diff itself is the input — playbooks are already readable YAML:
- name: Get changed Ansible files
run: git diff origin/${{ github.base_ref }}...HEAD -- '*.yml' '*.yaml' > ansible.diff
Cap the input size. If the combined text exceeds ~40,000 characters, split the review per file — giant inputs produce shallow reviews.
Step 2: Send the Diff to AI Code Review
A small Python step reads the diff, calls the LLM with a strict reviewer prompt, and writes the answer to a file:
- name: AI code review
env:
LLM_API_KEY: ${{ secrets.LLM_API_KEY }}
run: |
python3 - <<'EOF'
import json, os, urllib.request
diff = open('plan.txt').read()[:40000] if os.path.exists('plan.txt') else ''
diff += open('ansible.diff').read()[:20000] if os.path.exists('ansible.diff') else ''
prompt = f"""You are a senior DevOps code reviewer. Review this Terraform/Ansible change.
Report ONLY: 1) destructive or irreversible actions, 2) security risks
(open ports, secrets, broad IAM), 3) mistakes that would break idempotency
or cause downtime, 4) a one-line summary verdict: SAFE / REVIEW NEEDED / DANGEROUS.
Quote the exact lines behind every finding. Change:\n{diff}"""
body = json.dumps({"model": "gpt-4o-mini",
"messages": [{"role": "user", "content": prompt}], "temperature": 0.1}).encode()
req = urllib.request.Request("https://api.openai.com/v1/chat/completions",
data=body, headers={"Authorization": f"Bearer {os.environ['LLM_API_KEY']}",
"Content-Type": "application/json"})
out = json.load(urllib.request.urlopen(req, timeout=120))
open('review.md', 'w').write(out['choices'][0]['message']['content'])
EOF
Step 3: Post the AI Code Review as a PR Comment
- name: Comment on the pull request
if: github.event_name == 'pull_request'
env:
GH_TOKEN: ${{ github.token }}
run: gh pr comment ${{ github.event.pull_request.number }} --body-file review.md
Trigger the workflow on pull requests only:
name: iac-ai-review
on:
pull_request:
paths: ['**.tf', '**.yml', '**.yaml']
permissions:
contents: read
pull-requests: write
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with: { fetch-depth: 0 }

Step 4: Tune the Reviewer for Your Team
The prompt is your policy. Add team rules explicitly: “All resources must have Owner and Environment tags — flag any missing. EBS volumes must be encrypted. Ansible tasks must not use ignore_errors without a comment explaining why.” Reviewers also improve when you include the PR description, so the model can check whether the change matches the stated intent. Keep temperature low (0–0.2) for consistent, factual reviews.
For repositories that cannot send code to a cloud API, run the same workflow against a self-hosted model endpoint — the review step only needs an OpenAI-compatible URL. Many teams pair this with the patterns in our AI agents for sysadmins guide.
Troubleshooting
The review is generic and misses real issues. Your input is too big or your prompt too vague. Split by file, and add your team’s concrete rules to the prompt.
The workflow fails with 401. The LLM_API_KEY secret is missing or the workflow runs from a fork — secrets are not passed to fork PRs by default.
Terraform plan needs cloud credentials. For review-only pipelines, use terraform plan with a read-only role, or review the git diff of the .tf files instead of a live plan.
Too many comments on every push. Update a single comment instead of creating new ones: find the bot’s previous comment via the API and edit it, or only run the job when the PR is marked ready for review.
Conclusion
AI code review will not replace senior engineers, linters or policy-as-code — but it reads every line of every diff, every time, and explains risks in plain language. Add it to your Terraform and Ansible pipelines, tune the prompt with your team’s rules, and let humans focus on the design decisions only they can make. The result: fewer destructive plans merged by accident, and pull requests your team actually enjoys reviewing.