Skip to main content
hooksSource-backedReview first Safety Privacy
AWS logo

AWS CloudFormation Validator - Hooks

Validates AWS CloudFormation templates for syntax errors and best practices using cfn-lint v1.40.4+ and AWS CLI v2.27.54+.

by JSONbored·added 2025-09-19·
HarnessClaude Code
Trigger:PostToolUse
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://github.com/aws-cloudformation/cfn-lint, https://github.com/JSONbored/awesome-claude/blob/main/content/hooks/aws-cloudformation-validator.mdx
Brand
AWS
Brand domain
aws.amazon.com
Brand asset source
brandfetch
Safety notes
Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
Privacy notes
Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.
Author
JSONbored
Claim status
unclaimed
Last verified
2025-09-19

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

78

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Complete

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    Registry metadata indicates a reviewed listing.

    Done

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

CLI install

Copy-ready — paste the snippet to get started.

Install command

Provided

Config snippet

Provided

Copy snippet

Provided

Prerequisites

None

Platforms

1 listed

Difficulty

0/100

Adoption plan

Balanced adoption plan

Current risk score 16/100. Use staged verification before broader rollout.

Risk 16

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    Listing has review metadata.

    Done
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Required evidence gates are covered (5/6 signals complete).

Risk 15

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Present

Review metadata is present.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required evidence gates are covered for this preset.

Decision timeline

Decision timeline · balanced

5/6 steps complete with no blocking gaps for this preset.

Risk 14

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is available.

Done

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

No required blockers for this timeline preset.

Safety & privacy surface

Safety & privacy surface

1 safety and 1 privacy notes across 2 risk areas. Review closely: credentials & tokens, permissions & scopes.

2 areas
  • SafetyPermissions & scopesRuns automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
  • PrivacyCredentials & tokensReceives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.

Safety notes

  • Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.

Privacy notes

  • Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.

Schema details

Install type
cli
Reading time
1 min
Difficulty score
0
Troubleshooting
Yes
Breaking changes
No
Skill and platform metadata
Retrieval sources
https://github.com/aws-cloudformation/cfn-linthttps://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.htmlhttps://docs.aws.amazon.com/cli/latest/reference/cloudformation/validate-template.htmlhttps://github.com/stelligent/cfn_naghttps://www.checkov.io/https://code.claude.com/docs/en/hooks
Runtime and command metadata
Trigger
PostToolUse
Script language
bash
Script body
#!/usr/bin/env bash

# Read the tool input from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')

if [ -z "$FILE_PATH" ]; then
  exit 0
fi

# Check if it's a CloudFormation template
if [[ "$FILE_PATH" == *.cf.json ]] || [[ "$FILE_PATH" == *.cf.yaml ]] || [[ "$FILE_PATH" == *cloudformation*.yaml ]] || [[ "$FILE_PATH" == *cloudformation*.json ]]; then
  echo "☁️ Validating CloudFormation template $FILE_PATH..." >&2
  
  # Try cfn-lint first (preferred)
  if command -v cfn-lint &> /dev/null; then
    echo "Running cfn-lint validation..." >&2
    if cfn-lint "$FILE_PATH" 2>&1; then
      echo "✅ CloudFormation template validation passed" >&2
    else
      echo "❌ CloudFormation template validation failed" >&2
    fi
  elif command -v aws &> /dev/null; then
    echo "⚠️ cfn-lint not installed, using AWS CLI validation..." >&2
    if aws cloudformation validate-template --template-body "file://$FILE_PATH" 2>/dev/null; then
      echo "✅ Basic CloudFormation validation passed" >&2
    else
      echo "❌ CloudFormation template validation failed" >&2
    fi
  else
    echo "⚠️ Neither cfn-lint nor AWS CLI available for validation" >&2
  fi
else
  echo "File $FILE_PATH is not a CloudFormation template, skipping validation" >&2
fi

exit 0
Full copyable content
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/aws-cloudformation-validator.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}

About this resource

Features

  • Advanced CloudFormation template validation with cfn-lint v1.40.4+ supporting multi-region validation and custom rules
  • Syntax error detection and reporting with detailed line numbers, column positions, and error messages
  • AWS best practices compliance checking against AWS Well-Architected Framework guidelines and security standards
  • Type mismatch validation ensuring resource properties match AWS CloudFormation resource schemas
  • Fallback to AWS CLI v2.27.54+ validation when cfn-lint unavailable ensuring validation works in all environments
  • Support for JSON and YAML template formats with automatic format detection and appropriate parsing
  • SAM template support with automatic transformation to CloudFormation before validation
  • Comprehensive error reporting with severity levels (Error, Warning, Info) and actionable remediation guidance

Use Cases

  • Pre-deployment CloudFormation template validation ensuring templates are valid before stack creation
  • Infrastructure as Code quality assurance with automated validation catching errors early in development
  • CI/CD pipeline integration for AWS deployments preventing invalid templates from reaching production
  • Development workflow validation for cloud resources providing immediate feedback during template editing
  • Compliance checking against AWS best practices ensuring templates follow security and operational guidelines
  • Multi-region validation ensuring templates work correctly across different AWS regions and availability zones

CloudFormation Validation Tools Compared

This hook defaults to cfn-lint and falls back to the AWS CLI. How the common CloudFormation/IaC validators differ:

Tool What it checks Catches security issues? Needs AWS credentials?
cfn-lint (this hook) Template syntax, resource-property schemas, and AWS best-practice rules Partial (best-practice rules) No — fully local
aws cloudformation validate-template (fallback) Basic syntax and template structure via the CloudFormation API No Yes — calls the AWS API
cfn_nag Pattern-based scan for insecure infrastructure patterns (open security groups, wildcard IAM, unencrypted resources) Yes No — fully local
Checkov 1,000+ policy checks for security and compliance across CloudFormation, Terraform, and Kubernetes Yes No — fully local

For most pre-deployment checks, cfn-lint gives the best signal-to-noise on a single template; pair it with cfn_nag or Checkov when you need dedicated security/compliance scanning.

Installation

  1. Create hooks directory: mkdir -p .claude/hooks
  2. Create hook file: touch .claude/hooks/aws-cloudformation-validator.sh
  3. Make executable: chmod +x .claude/hooks/aws-cloudformation-validator.sh
  4. Add configuration from Hook Configuration section above to .claude/settings.json or ~/.claude/settings.json
  5. Alternative: Use the interactive /hooks command in Claude Code

Config paths

  • Local (not committed): .claude/settings.local.json
  • User settings (global): ~/.claude/settings.json
  • Project-wide (committed): .claude/settings.json

Requirements

  • Claude Code CLI installed
  • Project directory initialized
  • Bash shell available
  • jq installed (for JSON parsing)
  • cfn-lint ^1.40.0 (pip install cfn-lint) or AWS CLI v2.27.54+ (aws --version) for fallback validation
  • AWS CLI installed and configured (aws-cli 2.0+ recommended for CloudFormation validation)

Hook Configuration

{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/aws-cloudformation-validator.sh",
      "matchers": ["write", "edit"]
    }
  }
}

Hook Script

#!/usr/bin/env bash

# Read the tool input from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')

if [ -z "$FILE_PATH" ]; then
  exit 0
fi

# Check if it's a CloudFormation template
if [[ "$FILE_PATH" == *.cf.json ]] || [[ "$FILE_PATH" == *.cf.yaml ]] || [[ "$FILE_PATH" == *cloudformation*.yaml ]] || [[ "$FILE_PATH" == *cloudformation*.json ]]; then
  echo "☁️ Validating CloudFormation template $FILE_PATH..." >&2

  # Try cfn-lint first (preferred)
  if command -v cfn-lint &> /dev/null; then
    echo "Running cfn-lint validation..." >&2
    if cfn-lint "$FILE_PATH" 2>&1; then
      echo "✅ CloudFormation template validation passed" >&2
    else
      echo "❌ CloudFormation template validation failed" >&2
    fi
  elif command -v aws &> /dev/null; then
    echo "⚠️ cfn-lint not installed, using AWS CLI validation..." >&2
    if aws cloudformation validate-template --template-body "file://$FILE_PATH" 2>/dev/null; then
      echo "✅ Basic CloudFormation validation passed" >&2
    else
      echo "❌ CloudFormation template validation failed" >&2
    fi
  else
    echo "⚠️ Neither cfn-lint nor AWS CLI available for validation" >&2
  fi
else
  echo "File $FILE_PATH is not a CloudFormation template, skipping validation" >&2
fi

exit 0

Examples

AWS CloudFormation Validator Hook Script

Complete hook script that validates CloudFormation templates using cfn-lint or AWS CLI fallback

#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r ".tool_input.file_path // .tool_input.path // \"\"")
if [ -z "$FILE_PATH" ]; then exit 0; fi
if [[ "$FILE_PATH" == *.cf.json ]] || [[ "$FILE_PATH" == *.cf.yaml ]] || [[ "$FILE_PATH" == *cloudformation*.yaml ]] || [[ "$FILE_PATH" == *cloudformation*.json ]]; then
  echo "Validating CloudFormation template $FILE_PATH..." >&2
  if command -v cfn-lint &> /dev/null; then
    if cfn-lint "$FILE_PATH" 2>&1; then
      echo "CloudFormation template validation passed" >&2
    else
      echo "CloudFormation template validation failed" >&2
    fi
  elif command -v aws &> /dev/null; then
    if aws cloudformation validate-template --template-body "file://$FILE_PATH" 2>/dev/null; then
      echo "Basic CloudFormation validation passed" >&2
    else
      echo "CloudFormation template validation failed" >&2
    fi
  fi
fi
exit 0

Hook Configuration

Complete hook configuration for .claude/settings.json to enable CloudFormation validation on file writes and edits

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "./.claude/hooks/aws-cloudformation-validator.sh"
          }
        ]
      }
    ]
  }
}

Multi-Region Validation Hook

Enhanced hook script that validates CloudFormation templates against multiple AWS regions

#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r ".tool_input.file_path")
if [[ "$FILE_PATH" == *.yaml ]] || [[ "$FILE_PATH" == *.yml ]]; then
  if command -v cfn-lint &> /dev/null; then
    cfn-lint "$FILE_PATH" --regions us-east-1 us-west-2 --format json --output-file validation-results.json 2>&1
    if [ $? -eq 0 ]; then
      echo "Multi-region validation passed" >&2
    fi
  fi
fi
exit 0

Strict Validation with Error Blocking

Hook script that blocks operations on CloudFormation templates with validation errors

#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r ".tool_input.file_path")
if [[ "$FILE_PATH" == *.yaml ]] || [[ "$FILE_PATH" == *.json ]]; then
  if command -v cfn-lint &> /dev/null; then
    cfn-lint "$FILE_PATH" --ignore-checks W --format parseable 2>&1
    EXIT_CODE=$?
    if [ $EXIT_CODE -ne 0 ]; then
      echo "Template validation failed with errors" >&2
      exit 2
    fi
  fi
fi
exit 0

Template Detection with Schema Update

Hook script that detects CloudFormation templates by content and updates schemas before validation

#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r ".tool_input.file_path")
if grep -q "AWSTemplateFormatVersion" "$FILE_PATH" 2>/dev/null || grep -q "Transform: AWS::Serverless" "$FILE_PATH" 2>/dev/null; then
  if command -v cfn-lint &> /dev/null; then
    cfn-lint "$FILE_PATH" --update-specs 2>/dev/null
    cfn-lint "$FILE_PATH" 2>&1
  fi
fi
exit 0

Troubleshooting

Hook recognizes CloudFormation file but cfn-lint fails

Install cfn-lint: pip install cfn-lint or pipx install cfn-lint. Verify Python environment active: which python. Check template syntax with: cfn-lint --version. Review cfn-lint logs without 2>&1. Update CloudFormation schemas: cfn-lint --update-specs.

AWS CLI validation requires credentials unexpectedly

Use cfn-lint for offline validation instead. Or configure AWS credentials: aws configure. Use IAM role with minimal permissions. Skip AWS CLI fallback if credentials unavailable. Use AWS CLI with --no-verify-ssl for local testing only.

Template passes validation but hook shows failure message

Check exit code handling in script. Capture command output: OUTPUT=$(cfn-lint file) && echo success. Review conditional logic for success detection. Debug with: set -x in script. Verify cfn-lint exit codes: 0=success, 4=warnings, 8=errors.

Hook processes YAML files that aren't CloudFormation

Strengthen template detection regex. Check file content for AWSTemplateFormatVersion key: grep -q AWSTemplateFormatVersion file. Add explicit template marker in filename convention. Use content-based detection: grep -q "Resources:" file.

PostToolUse timing causes validation on incomplete writes

Verify file write completed before validation. Add small sleep: sleep 0.5 before validation. Check file size: [ -s "$FILE_PATH" ]. Use file lock detection if available. Validate file is not empty before processing.

cfn-lint reports errors but AWS CLI validation passes

cfn-lint performs deeper validation than AWS CLI. Review cfn-lint errors for best practices violations. AWS CLI only validates basic syntax. Use cfn-lint for comprehensive validation. Check cfn-lint rule documentation for specific error codes.

SAM template validation fails with cfn-lint

cfn-lint automatically transforms SAM templates. Verify Transform: AWS::Serverless-2016-10-31 is present. Update cfn-lint: pip install --upgrade cfn-lint. Check SAM template syntax matches SAM specification. Use --template parameter if needed.

Multi-region validation takes too long on large templates

Limit regions: cfn-lint file --regions us-east-1. Add timeout wrapper: timeout 60s cfn-lint file. Validate against single region first. Use --ignore-checks to skip non-critical rules. Consider validating in CI/CD instead of on every edit.

Source citations

Add this badge to your README

Show that AWS CloudFormation Validator - Hooks is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/hooks/aws-cloudformation-validator.svg)](https://heyclau.de/entry/hooks/aws-cloudformation-validator)

How it compares

AWS CloudFormation Validator - Hooks side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

Field

Validates AWS CloudFormation templates for syntax errors and best practices using cfn-lint v1.40.4+ and AWS CLI v2.27.54+.

Open dossier

A Stop hook that syncs your changed files to cloud storage when a Claude Code session ends, using rclone to push to S3, Google Cloud Storage, or any of its 70+ supported backends.

Open dossier

Validates environment variables, checks for required vars, and ensures proper configuration across environments.

Open dossier

Validates GraphQL schema files and checks for breaking changes when modified.

Open dossier
Next steps
Trust
Review statusReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backedSource-backedSource-backed
Submitter
Install riskReview firstReview firstReview firstReview first
Notes Safety Privacy Safety Privacy Safety Privacy Safety Privacy
BrandAWS logoAWSAWS logoAWS
Categoryhookshookshookshooks
Sourcesource-backedsource-backedsource-backedsource-backed
AuthorJSONboredJSONboredJSONboredJSONbored
Added2025-09-192025-09-192025-09-162025-09-19
Platforms
Claude Code
Claude Code
Claude Code
Claude Code
Source repo
Safety notesRuns automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.Runs automatically at session end and can create compressed archives of modified git files. Uploads backups through AWS CLI, Google Cloud SDK, or rclone when those tools and bucket variables are configured. Writes a temporary archive under /tmp when using the rclone fallback and removes it after the copy attempt.Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
Privacy notesReceives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.Sends modified file contents to the configured cloud storage destination. Uses locally configured cloud credentials and bucket environment variables but does not define or manage them. Backup archives may include source code, docs, generated files, and any unignored local changes listed by git diff.Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.
Prerequisites— none listed— none listed— none listed— none listed
Install
mkdir -p .claude/hooks && touch .claude/hooks/aws-cloudformation-validator.sh && chmod +x .claude/hooks/aws-cloudformation-validator.sh
mkdir -p .claude/hooks && touch .claude/hooks/cloud-backup-on-session-stop.sh && chmod +x .claude/hooks/cloud-backup-on-session-stop.sh
mkdir -p .claude/hooks && touch .claude/hooks/environment-variable-validator.sh && chmod +x .claude/hooks/environment-variable-validator.sh
mkdir -p .claude/hooks && touch .claude/hooks/graphql-schema-validator.sh && chmod +x .claude/hooks/graphql-schema-validator.sh
Config
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/aws-cloudformation-validator.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "stop": {
      "script": "./.claude/hooks/cloud-backup-on-session-stop.sh"
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/environment-variable-validator.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/graphql-schema-validator.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.