Infrastructure-as-code is powerful. You can define your entire cloud environment—servers, databases, networking, permissions—in version-controlled files. But that power comes with risk. A small typo in a Terraform file can provision 100 unnecessary servers. A misconfigured security group can expose your database to the internet. A forgotten variable can delete production data.
When Claude Code is used to modify infrastructure files, you need guardrails. You can’t afford to trust that a modification is safe without validation. This article shows you how to build a hook that automatically validates infrastructure changes before they’re applied. We’ll cover three major infrastructure-as-code formats: Terraform, CloudFormation, and Kubernetes manifests. For each, we’ll show you how to run dry-run commands, cost estimation checks, and schema validation—all automatically triggered by your hook.
Why Infrastructure Validation Matters: The Business Impact
Infrastructure files are different from application code. A bug in your Node.js application might affect some users. A bug in your Terraform configuration might:
- Provision resources you don’t need (unexpected AWS bills in the thousands)
- Delete critical infrastructure (downtime, data loss, business impact)
- Misconfigure security (compliance violations, regulatory fines)
- Create circular dependencies (undeployable states, rollback nightmares)
- Expose sensitive data (credentials, API keys in plain text)
The stakes justify an aggressive approach: block all infrastructure file modifications unless they pass automated validation. This is not paranoia. This is the difference between a minor mistake caught before deployment and an incident that takes down production.
Common infrastructure file patterns you need to protect:
terraform/
├── main.tf
├── variables.tf
├── outputs.tf
└── *.tfvars
cloudformation/
├── template.yaml
├── template.json
└── parameters/
kubernetes/
├── deployments.yaml
├── services.yaml
├── configmaps.yaml
└── kustomization.yaml
pulumi/
├── __main__.py
├── Pulumi.yaml
└── Pulumi.*.yaml
Every one of these file types can cause harm if modified without validation. Your hook should catch them all.
The Hidden Costs of Infrastructure Incidents
Before diving into validation mechanisms, let’s be clear about what we’re preventing. Infrastructure incidents aren’t like application bugs. An application bug affects some users. An infrastructure incident affects everyone, simultaneously, with cascading consequences.
A misconfigured security group that exposes your database to the internet doesn’t just lose customer data—it exposes personal information, triggers regulatory notifications, requires breach notification letters, potentially results in significant fines, and permanently damages customer trust. The incident response alone (forensic investigation, notification, customer support, regulatory compliance) costs hundreds of thousands of dollars.
A Terraform change that accidentally deletes a production database doesn’t just cause downtime—it potentially loses data, triggers a full incident response, requires recovery from backups (which might be stale), results in significant revenue loss during downtime, and creates massive liability if data can’t be recovered.
A Kubernetes configuration that allows privilege escalation doesn’t just fail a security check—it opens a pathway for attackers to compromise your entire infrastructure, potentially leading to data theft, service disruption, or further lateral attacks through your infrastructure.
These aren’t theoretical risks. Organizations spend millions annually on incident response, forensic investigation, regulatory compliance, and remediation for infrastructure mistakes that could have been caught by validation. The investment in validation infrastructure is insurance that pays for itself on the first prevented incident.
Understanding Infrastructure Validation: What You’re Actually Checking
Before blocking a change, you need to know what to validate. Infrastructure validation isn’t a single check—it’s a series of increasingly sophisticated checks that catch different categories of problems.
Syntax validation: Is the file syntactically correct? Terraform, CloudFormation, and Kubernetes all have strict syntax rules. A missing bracket, a typo in a keyword, improper indentation—these prevent the infrastructure from being deployed at all. Syntax validation catches the obvious stuff first. If syntax is broken, nothing else matters.
Schema validation: Does the configuration conform to expected resource schemas? A Terraform aws_instance must have a ami value; a Kubernetes Pod must have containers. Schema validation ensures you’re using the right resource types correctly. It checks that you haven’t tried to set properties that don’t exist, that required properties are present, that values are the right type.
Plan/dry-run analysis: What actually happens when you apply this change? Terraform’s plan command shows exactly what will be created, modified, or destroyed. This is critical because sometimes the semantic meaning of a change is different from what appears in the code. A property change might trigger a resource replacement (delete and recreate), causing downtime. The plan shows you this before it happens.
Cost estimation: How much will this change cost? AWS and Terraform have cost estimation tools that can warn about expensive changes. A simple change to an instance type might double your monthly bill. Cost estimation catches expensive mistakes before they happen.
Security scanning: Are there obvious misconfigurations? Missing encryption, overly permissive IAM policies, exposed secrets? Security scanning checks for common mistakes that developers make—things that won’t break deployment but will break security.
Your hook will perform all of these checks automatically, creating a multi-layer defense against infrastructure mistakes.
Building the Infrastructure Validation Hook: Layer by Layer
The infrastructure validation hook is sophisticated, but it’s built from simple, understandable pieces. Each piece checks one category of problems. Together, they create a comprehensive safety net.
Let’s start with the overall structure. The hook receives a file path and content. It identifies what kind of infrastructure file this is (Terraform, CloudFormation, Kubernetes). Then it runs type-specific validation. Finally, it reports what it found and blocks the change if there are problems.
Terraform Validation: The Three Checks
The Terraform section performs three key validation checks:
1. Syntax validation via terraform validate—this catches parse errors immediately. If the Terraform file has a syntax error, the validation command fails, and we block the change. This is the fastest check and catches the most obvious problems.
2. Plan execution via terraform plan -json—this shows exactly what will be created, modified, or deleted. Terraform’s plan command is incredibly valuable because it shows you what will actually happen, not just whether the configuration is syntactically correct. You might have valid syntax that causes unintended consequences (deleting resources, creating expensive resources, causing downtime).
3. Destructive change detection—we specifically flag any resources that will be deleted. A resource deletion in Terraform’s plan is a warning sign. You might be accidentally deleting something critical. The hook alerts you to any destructive changes so you can review them carefully.
Terraform’s -json output format makes it easy to parse and extract resource changes programmatically. You can analyze exactly which resources will be affected and how.
CloudFormation Validation: Pattern-Based Scanning
CloudFormation validation is trickier because we can’t easily run AWS API calls. Instead, we use pattern-based scanning:
1. Parse the template to ensure it’s valid JSON/YAML. CloudFormation templates must be perfectly formed before deployment. Invalid JSON or YAML means the deployment will fail.
2. Check for security anti-patterns—overly permissive CIDR blocks (like 0.0.0.0/0 which means “the entire internet”), disabled versioning, visible passwords. These are common mistakes that don’t break deployment but break security.
3. Warn about best practices—default passwords, missing NoEcho markers on sensitive values. These checks catch the most common CloudFormation mistakes.
These pattern-based checks catch the most common CloudFormation mistakes without needing AWS API calls. You’re doing static analysis of the template file itself.
Kubernetes Manifest Validation: Operational Best Practices
Kubernetes validation focuses on pod security and operational best practices:
1. Required fields validation—every manifest needs kind: and metadata:. These are the bare minimum for a valid Kubernetes resource.
2. Security context checks—warns if running privileged or allowing privilege escalation. Running pods in privileged mode is a security risk. These checks catch the most obvious security configurations.
3. Image policy checks—warns about :latest tags and missing imagePullPolicy. Using the :latest tag means you get unpredictable image versions. The image changes every time you deploy without you realizing it.
4. Resource limits—warns if pods lack requests or limits, which breaks scheduling. Without resource requests, the Kubernetes scheduler can’t properly schedule pods. Without resource limits, a single pod can consume all resources and crash the entire cluster.
5. Probe validation—warns if Deployments lack liveness probes. Without liveness probes, unhealthy pods don’t get restarted. They just sit there broken.
Each of these checks catches a different category of operational problem. Together, they create a comprehensive set of guardrails for Kubernetes manifests.
Cost Estimation Integration: Catching Expensive Surprises
For significant infrastructure changes, integrate cost estimation. This is where you catch expensive mistakes before they happen. A simple change to an instance type might double your monthly bill. Without cost estimation, you won’t know until the AWS bill arrives. With it, you catch it before deployment.
Infracost is a tool that integrates with Terraform to estimate AWS costs. If you’re using AWS, integrating Infracost into your validation hook is a smart move. You can set thresholds—if a change will cost more than $1000 per month, the hook flags it for review. If a change will cost more than the entire project budget, the hook blocks it entirely.
This prevents expensive mistakes. You catch them at change-time, not at bill-time.
Real-World Incident Prevention: How This Hook Saves Your Infrastructure
Let’s examine how this hook prevents real infrastructure disasters. These are actual patterns from real incidents.
Incident 1: The Accidental Database Deletion
A developer asks Claude Code: “Update the database configuration in our infrastructure code to use a smaller instance type for cost savings.”
Without the hook, Claude Code might rewrite the Terraform file, changing instance_class = "db.r5.xlarge" to instance_class = "db.t2.micro". This change modifies the instance type, but it also triggers a replacement (new instance), causing downtime and potential data loss. Your database goes offline. Customer-facing services fail. You spend 6 hours recovering.
With the hook:
- Claude Code detects the
.tffile modification - The hook runs
terraform planto show what would actually happen - The plan reveals: “aws_db_instance will be replaced”
- The hook blocks the change with a warning about destructive changes
- The developer or DevOps engineer reviews the plan and rejects it
- Instead, they create a proper migration plan with backups
The hook catches the problem before it causes an incident. Instead of “delete instance and hope the backups work,” you have a planned, tested migration.
Incident 2: The Overly Permissive Security Group
A developer is trying to open a port for a new service and asks: “Allow traffic on port 5432 from the internet to our database security group.”
Without validation, this creates a security group rule allowing 0.0.0.0/0 (the entire internet) to access the database on port 5432. This is a critical security misconfiguration. Every attacker on the internet can try to connect to your database. Your credentials are the only protection, and password brute-forcing is trivially easy.
With the hook:
- Claude Code detects the CloudFormation modification
- The hook scans the template and finds the pattern:
CidrIp: 0.0.0.0/0+DBPort - The hook blocks it with a security warning
- The developer corrects it to only allow traffic from the application servers (maybe 10.0.0.0/8 instead of 0.0.0.0/0)
The hook catches the security misconfiguration before it causes a compromise. You’ve prevented exposing your database to the internet.
Incident 3: The Kubernetes Image Drift
A developer tries to update a Kubernetes deployment to use a new image version: “Update the app deployment to use the latest image version.”
Without validation, they might use image: myapp:latest, which causes non-deterministic behavior. The image changes with every pod restart without you realizing it. You deploy version 1.2.3, but the pod that starts up 6 hours later might be running version 1.3.0 if someone pushed a new :latest tag. Your deployment is non-deterministic and unreproducible.
With the hook:
- Claude Code detects the Kubernetes YAML modification
- The hook scans for
:latesttags and flags it - The developer is forced to specify an explicit version:
myapp:v1.2.3 - The deployment is now reproducible and auditable
The hook forces you toward best practices. You can’t accidentally use :latest. Every deployment uses a specific version.
Organizing Infrastructure by Environment: Different Rules for Different Contexts
A robust setup separates infrastructure by environment with different validation rules. Your development infrastructure is less critical than your production infrastructure. You can afford looser validation in dev, but strict validation in production.
infrastructure/
├── shared/ # Shared resources (VPC, etc.)
│ └── main.tf
├── dev/
│ ├── main.tf # Stricter validation bypassed
│ └── variables.tf
├── staging/
│ ├── main.tf # Standard validation
│ └── variables.tf
└── prod/
├── main.tf # Strictest validation
└── variables.tf
Your hook can adjust validation strictness based on which directory is being modified. Changes to /prod/ require plan review, cost analysis, and security scan. Changes to /dev/ are warned but allowed with logging.
This lets you be protective of production while allowing faster iteration in development. It’s a risk-appropriate approach.
Testing the Validation Hook: Ensuring It Works
You need comprehensive tests for your infrastructure validation hook. Test with actual infrastructure files—good ones and bad ones.
Test cases should include:
- Terraform files with syntax errors
- Terraform files that would create expensive resources
- Terraform files with destructive changes
- CloudFormation templates with security issues
- CloudFormation templates with default passwords
- Kubernetes manifests with privileged pods
- Kubernetes manifests with missing resource limits
- Valid infrastructure files that should pass validation
For each test case, verify that the hook allows or blocks as expected. These tests ensure your hook is working correctly before you deploy it.
Integration with Deployment Systems: Real Automation
For production workflows, integrate your hook with CI/CD. When a developer pushes infrastructure code, the CI pipeline runs validation. If validation fails, the PR gets a comment explaining why. If validation passes, the PR can proceed to manual review.
This creates a two-stage process: automated validation (fast, comprehensive, catches obvious mistakes) plus human review (catches logic errors, architectural concerns, cost implications). Together, they create a safety net that prevents most infrastructure mistakes.
Best Practices: The Rules That Keep You Safe
1. Always require human approval for infrastructure changes, even if validation passes. Infrastructure is too critical to automate completely. Validation catches mistakes, but humans catch architectural problems.
2. Use separate approval workflows for staging vs. production. Staging changes can be faster; production changes should be slower and more careful. A critical fix can go to staging quickly. Production requires more deliberation.
3. Keep dry-run output available for review. When validation fails, humans need to see exactly what would happen. The terraform plan output is invaluable.
4. Integrate with your secrets management. Infrastructure files often reference credentials—use vaults, not stored secrets. Your validation hook can check for hardcoded secrets and block files that contain them.
5. Test infrastructure changes in staging first. Your hook validates syntax and security. Actual deployment testing must happen in staging environments. You catch bugs by running it, not by reading the code.
The Philosophy Behind Infrastructure-as-Code Validation
There’s a deeper principle at work here that’s worth understanding. Infrastructure files are unique because they express intent in a way that gets executed mechanically. Unlike application code, where bugs manifest as edge cases and error handling can catch mistakes, infrastructure code either works perfectly or fails catastrophically.
A typo in your Node.js router might cause some requests to fail, and your error handling will catch it. A typo in your Terraform file might delete your database. That asymmetry—where the downside is extreme and the upside of catching it is enormous—justifies putting validation gates in front of infrastructure changes.
The hook pattern reflects a philosophy: infrastructure is too dangerous to trust implicitly. We validate first, always. We show the consequences before executing them. We build in multiple layers of safety because the cost of being wrong is unacceptable.
This is why the plan output is so important. When you run terraform plan, Terraform shows you exactly what will happen before it happens. This is the human-review stage. A system that forces this to be visible, that makes it impossible to change infrastructure without seeing the plan first, prevents disasters.
Handling Validation Failures: Clear Feedback
When validation fails, your hook needs to communicate clearly why it failed and what needs to be fixed. Your error messages should be:
- Specific: Tell the developer exactly what the problem is
- Actionable: Tell them how to fix it
- Context-rich: Show them the relevant parts of the file or plan
- Not accusatory: This is helping, not judging
A good error message explains what validation found, why it’s a problem, and what to do about it. A bad error message just says “validation failed” with no explanation.
Long-Term Benefits: The Compounding Payoff
Short-term: validation catches mistakes before they become incidents. Your developers get immediate feedback when they make a mistake. You prevent a few incidents per month.
Long-term: your team learns to think about infrastructure more carefully. They understand what their changes do. They understand the consequences. They become better infrastructure engineers. The culture shifts toward careful, validated changes.
Most importantly: your infrastructure becomes predictable and auditable. Every change went through validation. You have a record of what was deployed and why. When something goes wrong, you can audit the change history. When you need to understand the architecture, you have the validated infrastructure code as your source of truth.
Scaling Validation Across Multiple Infrastructure Repositories
As your infrastructure grows, you might have multiple repositories: one for Terraform, one for CloudFormation, separate Kubernetes manifests. Your validation needs to work across all of them.
The hook pattern scales naturally. A single hook can detect file types and dispatch to type-specific validators. You can maintain a central hook that’s used by all repositories. Updates happen once, benefit everywhere.
Or you can have type-specific hooks. The Terraform repo has a Terraform validator hook. The CloudFormation repo has a CloudFormation hook. Each is optimized for its type. This gives you flexibility at the cost of more hook management.
Choose based on your organization’s structure. Centralized is simpler. Distributed is more flexible.
Learning from Validation Failures
When a validation fails, it’s not just a blocker—it’s a learning opportunity. A developer tries to create a rule that would expose their database to the internet. The validation blocks it. They learn something: “Oh, I shouldn’t use 0.0.0.0/0 for database security groups.”
This educational value is underrated. Over time, your team learns which patterns are dangerous. They learn how to write safe infrastructure code. They start thinking defensively before they write code.
Capture these learning moments. When validation fails, provide clear explanations. Provide links to documentation about why the pattern is wrong. Provide examples of correct patterns. Turn every validation failure into a teaching moment.
Integration with Your Incident Response Process
When an infrastructure change causes an incident, your validation hook becomes crucial evidence. You can replay what happened. Did the change pass validation? If not, why not? If it did, what did validation miss?
This post-incident analysis lets you improve validation. “Oh, we validated that the security group change was syntactically correct, but we didn’t check that it was safe. Let’s add that check.”
Your infrastructure validation system becomes part of your incident response capability. It’s not just preventing incidents—it’s helping you understand and prevent future incidents.
Handling Special Cases and Exceptions
Real infrastructure has special cases. Sometimes you need to do something unusual that doesn’t pass normal validation. Maybe you’re working around a bug in a tool. Maybe you’re doing a carefully planned but risky migration.
Your hook needs to handle this. Options:
1. Approval workflows: High-risk changes that still pass all checks require explicit approval from a senior engineer.
2. Escape hatches: Documented ways to bypass validation for emergencies, with strong accountability (all changes logged and audited).
3. Environment-specific rules: Different rules for different environments. Dev allows more. Prod is stricter.
4. Gradual rollout: Test in dev and staging with looser validation. Only production has strict validation.
These patterns let you be strict without being inflexible. Real organizations need both safety and pragmatism.
Validation Performance and Latency
Running Terraform plan, scanning large YAML files, checking for hundreds of security patterns—this takes time. For a large infrastructure file, validation might take 10 seconds. Is that acceptable?
It depends. If you’re making changes frequently, 10 seconds per change adds up. You might optimize by:
1. Parallel validation: Run multiple checks in parallel (Terraform plan and security scan simultaneously).
2. Incremental validation: Only validate the file that changed, not the entire infrastructure.
3. Caching: Cache validation results and only re-validate if the file actually changed.
4. Background validation: Run expensive checks asynchronously and report async results.
These optimizations let you validate thoroughly without blocking the developer for minutes.
Metrics and Monitoring for Infrastructure Validation
Track these metrics to measure your infrastructure governance:
- Validation failure rate: What percentage of changes fail validation? If it’s too high, your rules are too strict. If it’s too low, they might be too lenient.
- Time to fix validation failures: When someone encounters a validation failure, how long does it take them to fix it? Long times might indicate your error messages aren’t clear enough.
- False positive rate: How many changes pass validation but cause problems anyway? This indicates gaps in your validation logic.
- Incident rate: How many production incidents are caused by infrastructure changes? Trending down is good.
These metrics show whether your validation is actually improving safety or just adding friction.
Adapting Validation Across Infrastructure Complexity Levels
Infrastructure varies wildly in complexity. A simple web server deployment is straightforward. A distributed microservices architecture is intricate. A multi-region, multi-cloud setup with failover is extraordinarily complex. Your validation strategy needs to scale with complexity.
For simple infrastructure, basic validation suffices. Syntax checks, schema validation, basic security scanning. For complex infrastructure, you need semantic validation—understanding how components interact, what side effects changes have, how load balancing and failover work.
This progression mirrors real-world development. A startup uses simple CloudFormation templates with basic validation. As they grow and complexity increases, they upgrade to Terraform with plan analysis. As they scale further, they add cost estimation and advanced security analysis. Eventually, they build custom validators that understand their specific infrastructure patterns.
The key insight is matching validation complexity to infrastructure complexity. You’re not building an over-engineered system that makes simple changes painful. You’re building a system that scales from simple to complex. A developer deploying a simple update to a development environment experiences fast, lightweight validation. A production change to critical infrastructure gets heavy analysis. The validation meets the situation’s needs.
This scaling also applies to approval workflows. A development change might only need validation to pass. A production change might need validation to pass plus human approval. A change that affects billing might need validation, approval, and a cost threshold waiver from a manager. You’re layering governance proportional to risk.
Building Institutional Knowledge Through Validation
Over time, your infrastructure validation becomes institutional knowledge. The hooks encode lessons learned from past incidents. “We don’t allow overly permissive security groups because that caused incident X in 2024.” “We enforce resource limits on Kubernetes pods because we had a cluster crash when one pod consumed all memory.”
New team members inherit this knowledge through the validation system. They don’t have to learn lessons the hard way. The system enforces best practices automatically. They can reason about why each rule exists by understanding the incidents and lessons that created them.
Documentation matters here. Each validation rule should have a comment explaining its origin. “This rule blocks privileged containers (reason: container escape in 2023 led to host compromise).” “This rule requires resource limits (reason: 2024 incident where app pod consumed all cluster memory).” These explanations turn validation rules from arbitrary restrictions into learning tools.
Over years, this becomes a powerful onboarding tool. New infrastructure engineers understand not just the rules but the reasoning. They understand why infrastructure safety matters. They become more thoughtful engineers because they’ve inherited lessons from incidents they didn’t experience directly.
Evolution of Validation Sophistication
Infrastructure validation isn’t static. It evolves as your infrastructure grows more complex and your team gains more experience.
Stage 1 (Early): Basic validation. Syntax checks. Schema validation. “Is this even valid infrastructure code?” You catch the most obvious mistakes.
Stage 2 (Growing): Plan-based validation. Terraform plans showing what will actually happen. Dry-run commands for CloudFormation. You understand the consequences of changes.
Stage 3 (Mature): Semantic validation. Understanding how components interact. Cost estimation. Security scanning. You understand not just what will happen, but whether it’s safe and economical.
Stage 4 (Advanced): Policy validation. Custom rules specific to your organization. Compliance checking. Quota checking. You enforce organizational standards through code.
Stage 5 (Enterprise): Multi-layer validation with approval workflows. Different rules for different environments. Integration with incident management. Self-healing validation that can fix common issues automatically.
Most organizations start at Stage 1 and gradually progress as they gain experience. The key is starting with the value you can deliver immediately, then adding layers as you grow. Don’t try to jump straight to Stage 5—the complexity will paralyze you.
Handling Emergency Changes and Validation Bypass
Real infrastructure sometimes requires urgent changes that might not have time for full validation. A security incident requires immediate patching. A critical bug needs emergency fixes. How do you handle validation without paralyzing emergency response?
The answer is structured bypass with strong accountability. You can allow validation bypass, but it requires:
- Explicit approval from authorized person (on-call security or infrastructure lead)
- Detailed documentation of why bypass was necessary
- Automatic escalation (flagged for post-incident review)
- Time limit (bypass is only allowed for 24 hours, then expires)
- Audit trail (all bypasses logged and reviewed)
This approach lets you move fast in emergencies while maintaining accountability. You’re not just disabling validation—you’re documenting that you did it, why you did it, and you’ll review it later.
After the emergency is over, you analyze what caused the emergency. Was validation preventing legitimate changes? Should you adjust validation rules? Should you add faster approval paths for known-safe changes? You learn from each emergency bypass and improve your validation accordingly.
Validation Across Different Team Structures
Infrastructure validation works differently depending on your team structure.
Centralized infrastructure team: One team manages all infrastructure. Validation rules are determined by that team. Changes flow through them. This is straightforward—one set of rules, one approval process.
Distributed infrastructure (teams own their infrastructure): Each team manages their own infrastructure. Different teams have different risk tolerances and requirements. Your validation system needs to support environment-specific rules. Rules for staging are looser than rules for production. Rules for team A might be stricter than rules for team B if they handle sensitive data.
Hybrid (platform team + application teams): Platform team owns shared infrastructure (VPC, database clusters, etc.). Application teams own their own infrastructure (containers, services, etc.). Validation needs to understand these boundaries. Changes to shared infrastructure require stricter validation. Changes to application infrastructure can be lighter.
The key is making your validation system flexible enough to support your organizational structure, not forcing your organizational structure to match the validation system.
The Cultural Shift: From Hope to Confidence
When you implement infrastructure validation, something shifts in your organization’s culture. From “we hope our infrastructure code is correct” to “we know our infrastructure code passed multiple automated checks and human review.”
This shift manifests in higher confidence. Teams move faster because they trust their changes. New deployments feel safer. Incidents become rarer. People sleep better knowing that bad infrastructure changes are caught before deployment.
This is the real value of infrastructure validation: not just preventing incidents, but changing how your organization thinks about safety and risk.
-iNet