You want to enforce security and compliance policies on CloudFormation templates before they are deployed - for example, ensuring all S3 buckets have encryption and all security groups don't allow 0.0.0.0/0 ingress. How do you implement this with CloudFormation Guard?
Quick Answer
CloudFormation Guard (cfn-guard) is a policy-as-code tool that validates CloudFormation templates against rules written in a domain-specific language. Integrate it into CI/CD pipelines to block non-compliant templates before deployment, and use it with CloudFormation Hooks for server-side enforcement.
Detailed Answer
CloudFormation Guard Overview
Cfn-guard is an open-source CLI tool that evaluates CloudFormation (and other JSON/YAML) templates against policy rules. Rules are written in a purpose-built DSL that reads naturally: AWS::S3::Bucket { Properties.BucketEncryption EXISTS }. It runs offline (no AWS API calls needed), making it fast and suitable for CI/CD pipelines and local development. Guard 2.x introduced a significantly improved rule language with support for custom messages, cross-resource checks, and when-conditions.
Rule Writing
Guard rules use a declarative syntax that specifies resource type filters and property assertions. You can check for existence, specific values, ranges, regex patterns, and nested properties. Rules can be grouped into named rule sets with descriptions. The when clause adds conditional logic: only check multi-AZ on RDS if the environment parameter is 'prod'. Custom error messages make violations actionable for developers.
CloudFormation Hooks
For server-side enforcement, register Guard rules as CloudFormation Hooks. Hooks run automatically during stack operations and can block non-compliant resource creation/modification at the CloudFormation level, regardless of whether the deployment comes from CLI, console, or CI/CD. This provides defense-in-depth: even if a developer bypasses CI/CD policy checks, the Hook catches the violation.
Integration Patterns
Run cfn-guard in CI/CD as a pre-deployment gate: cfn-guard validate -d template.yaml -r rules/. Store rules in a central Git repository shared across teams. Use the cfn-guard test command to unit test your rules against sample templates. Combine with AWS Config conformance packs for runtime compliance monitoring.