AWS Builder Center
Part 1: Building a Resiliency PR Agent — Static Rules + AI Skills in 500 Lines

Part 1: Building a Resiliency PR Agent — Static Rules + AI Skills in 500 Lines

*Part 1 of 2 in the "Shift-Left Resiliency" series*

TL;DR: We build a resiliency reviewer for IaC pull requests in ~500 lines of Python. It has two layers: (1) static YAML rules that catch common single-AZ mistakes instantly, and (2) an AI layer powered by Amazon Bedrock that dynamically loads domain-expert "skills" per resource type to detect cross-service resiliency gaps. The whole thing runs as a GitHub Action — no server, no database, no infrastructure to maintain.


Tags:  #Resilience   #DevOps   #Well-Architected   #InfrastructureAsCode   #AI/ML   #Bedrock 
Series: Shift-Left Resiliency (Part 1 of 2)



What We're Building

By the end of this post, you'll understand how to build a GitHub Action that:
  1. Parses Terraform (HCL) and CloudFormation (YAML/JSON) into a structured resource inventory
  1. Runs deterministic rule checks against those resources (no AWS credentials needed)
  1. Dynamically loads domain-expert AI "skills" based on which resource types are present
  1. Sends the resources + relevant skills to Amazon Bedrock for contextual analysis
  1. Outputs findings as CLI tables, PR comments, or SARIF for inline annotations



Architecture Overview

┌─────────────────────────────────────────────────────┐
│ Resiliency AI Agent │
│ │
.tf / .yaml ─────┤ 1. Scanner (python-hcl2 / PyYAML) │
files │ └── Extract resources + line numbers │
│ │
│ 2. Rules Engine (YAML rules → deterministic) │
│ └── Static findings (HIGH/MEDIUM/LOW) │
│ │
│ 3. Skill Loader (manifest.yaml matching) │
│ └── Load only relevant SKILL.md files │
│ │
│ 4. AI Reviewer (Amazon Bedrock) │
│ └── Cross-service reasoning + skill context │
│ │
│ 5. Reporter (CLI / PR comment / SARIF) │
└─────────────────────────────────────────────────────┘
The design principle: Layer 2 always runs (zero dependencies, instant results). Layer 4 is additive — it builds on the static findings with deeper, cross-service analysis, but requires AWS credentials.
Resiliency AI Agent - Pipeline




Step 1: The Scanner — Parsing IaC Into Resources

The scanner's job is simple: turn  .tf  and  .yaml/.json  files into a flat list of resources with their properties and source line numbers.
# src/scanner.py (simplified)
import hcl2, yaml, json
from pathlib import Path

def scan_file(filepath: str) -> list[dict]:
path = Path(filepath)
if path.suffix == ".tf":
return _parse_terraform(path)
elif path.suffix in (".yaml", ".yml"):
return _parse_cloudformation_yaml(path)
elif path.suffix == ".json":
return _parse_cloudformation_json(path)
return []

def scan_directory(directory: str) -> list[dict]:
resources = []
for path in Path(directory).rglob("*"):
if path.suffix in (".tf", ".yaml", ".yml", ".json"):
if ".terraform" not in str(path):
resources.extend(scan_file(str(path)))
return resources
For Terraform, we use  python-hcl2  — a proper HCL parser (not regex). Each resource gets:
{
"source": "modules/database/main.tf",
"format": "terraform",
"resource_type": "aws_db_instance",
"resource_name": "three_tier_db",
"config": {"engine": "mysql", "multi_az": False, ...},
"line": 14, # ← exact line for SARIF annotations
}
The line number is found by regex-searching the raw file for the resource declaration. This is what allows SARIF to produce inline annotations on the exact line in the PR diff.



Step 2: Static Rules — Fast, Deterministic, Zero-Credential

Rules are defined in YAML files — one per domain:
rules/
├── compute.yaml # ASG 3+ AZs, EKS multi-AZ, Lambda VPC subnets
├── database.yaml # RDS Multi-AZ, backups, ElastiCache failover
├── networking.yaml # NAT Gateway SPOF, ALB multi-AZ, cross-zone LB
└── storage.yaml # S3 versioning, EBS snapshots
Each rule is a declarative check:
# rules/database.yaml
rules:
- id: DB-001
name: RDS must be Multi-AZ
severity: HIGH
description: >
RDS instances should have Multi-AZ enabled for automatic
failover during AZ failure
resource_types:
- aws_db_instance # Terraform
- AWS::RDS::DBInstance # CloudFormation
remediation: |
Enable Multi-AZ:
```hcl
resource "aws_db_instance" "main" {
multi_az = true
}
```
The rules engine evaluates each rule against matching resources:
# src/rules_engine.py (core logic)
def check_resources(resources, rules):
findings = []
for resource in resources:
for rule in rules:
if resource["resource_type"] in rule["resource_types"]:
if _is_violated(rule, resource):
findings.append(Finding(
rule_id=rule["id"],
severity=rule["severity"],
resource_name=resource["resource_name"],
line=resource["line"],
...
))
return findings
Special case: aggregate rules. Some checks need visibility across the entire resource set. For example,  NET-001  (single NAT Gateway) counts all  aws_nat_gateway  blocks. If there's exactly one and it doesn't use  count  or  for_each , it's flagged as a single point of failure:
def _check_nat_gateway_redundancy(resources, rule):
nat_gateways = [r for r in resources
if r["resource_type"] == "aws_nat_gateway"]
if len(nat_gateways) != 1:
return [] # 0 = not our concern; 2+ = redundant
config = nat_gateways[0]["config"]
if "count" in config or "for_each" in config:
return [] # fan-out pattern (one per AZ) — OK
return [make_finding(rule, nat_gateways[0])]
This is important: a single NAT Gateway resource block with  count = length(var.azs)  deploys one per AZ — that's fine. Only a hardcoded single block is a SPOF.



Step 3: Dynamic Skills — Only Load What's Relevant

Here's what makes this agent different from a static linter: the AI layer gets domain-specific expertise injected based on what's actually in the PR.
Dynamic Skill Loading

Each skill lives in its own directory:
skills/
├── compute-asg/
│ ├── manifest.yaml # triggers: [aws_autoscaling_group, aws_launch_template]
│ └── SKILL.md # Deep knowledge: static stability sizing, health checks, ...
├── eks-zonal/
│ ├── manifest.yaml # triggers: [aws_eks_cluster, aws_eks_node_group]
│ └── SKILL.md # Zonal shift, pod topology, EBS pinning, ...
├── networking-ha/
│ ├── manifest.yaml # triggers: [aws_nat_gateway, aws_lb, aws_alb, ...]
│ └── SKILL.md # NAT-per-AZ, cross-zone LB, Route53 failover, ...
└── rds-resilience/
├── manifest.yaml # triggers: [aws_db_instance, aws_rds_cluster, ...]
└── SKILL.md # Multi-AZ, Aurora topology, failover times, ...
The loader matches triggers against detected resource types:
# src/skill_loader.py
def load_matching_skills(resources, skills_dir="skills/"):
resource_types = {r["resource_type"] for r in resources}
loaded = []
for skill_dir in Path(skills_dir).iterdir():
manifest = yaml.safe_load((skill_dir / "manifest.yaml").read_text())
triggers = set(manifest["triggers"])
if resource_types & triggers: # set intersection
content = (skill_dir / "SKILL.md").read_text()
loaded.append(LoadedSkill(
name=manifest["name"],
content=content,
triggers=list(triggers),
))
return loaded
If a PR only touches RDS and networking resources, only those 2 skills are loaded — the EKS skill never enters the prompt. This keeps context focused and costs low.



Step 4: AI Reviewer — Bedrock with Skill-Powered Context

The AI reviewer sends resources + loaded skills to Amazon Bedrock:
# src/ai_reviewer.py (simplified)
def analyze_with_bedrock(resources, skills, region="us-west-2", model_id=DEFAULT_MODEL_ID):
skills_context = format_skills_for_prompt(skills)
system_prompt = f"""You are a cloud infrastructure resiliency reviewer
specializing in the AWS Well-Architected Reliability Pillar.
{skills_context}
For each finding, provide:
- Severity: HIGH/MEDIUM/LOW
- The Well-Architected reference (REL10-BP01, REL11-BP05, etc.)
- The specific resource and what's wrong
- Why it matters (what happens during an AZ failure)
- How to fix it (with IaC code snippet)
Output as JSON array."""
body = {
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 4096,
"temperature": 0.1,
"system": system_prompt,
"messages": [{"role": "user", "content": f"Analyze: {json.dumps(resources)}"}]
}
bedrock = boto3.client("bedrock-runtime", region_name=region)
response = bedrock.invoke_model(body=json.dumps(body), modelId=model_id, ...)
return extract_findings(response)
Key design decisions:
  •  temperature: 0.1  — Near-deterministic output. We want consistent findings, not creative prose.
  •  invoke_model  (not  converse ) — Direct Anthropic format gives us full control over system prompt structure.
  • Graceful fallback — If credentials are missing or Bedrock fails, it returns  []  and static findings still get reported. The agent never crashes.

What the AI catches that rules can't:

A linter sees: "RDS is not Multi-AZ" → FAIL.
The AI sees: "Your EKS pods run across 3 AZs, but your database is pinned to us-west-2a. If that AZ fails, 2/3 of your compute becomes useless because it can't reach the database. The blast radius expands from 33% to 100%."
Cross-service reasoning — understanding how the composition of resources creates failure modes that no single resource check can detect.
Linter vs AI Agent




Step 5: Output Formats

The reporter generates four formats from the same findings:
Format
Use case
Output
 --format cli 
Local development
Colored terminal table
 --format pr 
GitHub Action
Markdown table for PR comment
 --format json 
Automation/scripting
Machine-readable JSON
 --format sarif 
GitHub Code Scanning
SARIF 2.1.0 → inline annotations
SARIF is what makes the findings appear inline on the exact line in the PR diff (like CodeQL findings), rather than just a comment at the bottom.



The CLI

Everything hangs off a single  scan  command:
# Static rules only — zero AWS credentials needed
python src/main.py scan path/to/terraform/

# Add AI analysis (needs Bedrock access)
python src/main.py scan path/to/terraform/ --ai --format cli --verbose

# Generate SARIF for GitHub Code Scanning
python src/main.py scan . --ai --format sarif --output findings.sarif

# Filter by severity
python src/main.py scan . --ai --severity MEDIUM



Project Layout

resiliency-ai-agent-v1/
├── action.yml # GitHub Action (composite)
├── requirements.txt # boto3, PyYAML, python-hcl2, click
├── src/
│ ├── main.py # CLI entry point (click)
│ ├── scanner.py # Terraform + CloudFormation parser
│ ├── rules_engine.py # Static YAML rule evaluator
│ ├── skill_loader.py # Dynamic skill matching
│ ├── ai_reviewer.py # Bedrock integration
│ ├── sarif_reporter.py # SARIF 2.1.0 output
│ └── reporter.py # CLI + PR comment formatting
├── rules/ # Static rule definitions (YAML)
├── skills/ # Domain expertise (manifest + SKILL.md)
├── scripts/
│ └── setup-oidc-role.sh # One-time AWS OIDC setup
├── tests/ # Unit tests
└── docs/
└── consumer-workflow-example.yml
Total: ~500 lines of application code (excluding skills content and rules YAML). The agent is deliberately thin — the intelligence comes from (a) the rules being specific and correct, and (b) the skills being rich domain knowledge that the AI can apply contextually.



What's Next

In  Part 2 , we ship this to production:
  • The  action.yml  composite action (copy-paste installation)
  • OIDC-only authentication (no stored AWS keys, ever)
  • Real test results: 12 findings on a 3-tier Terraform app
  • SARIF → inline annotations in a live PR




The views expressed in this post are my own and do not necessarily reflect the position of my employer. This is a personal project shared for educational purposes.
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