AWS CloudFormation Linter (cfn-lint)
cfn-lint is an open-source static analysis tool developed by AWS that checks CloudFormation templates (YAML/JSON) for potential errors, adherence to AWS best practices, and valid resource configurations. It validates templates against the AWS CloudFormation resource provider schemas and additional checks, aiming to catch issues before deployment. The project is actively maintained with frequent updates, often including new CloudFormation schemas and linting rules.
Warnings
- breaking Python 3.9 support has been removed as of cfn-lint v1.47.0. Users on Python 3.9 or older must upgrade their Python environment to 3.10 or newer.
- breaking cfn-lint v1 introduced major breaking changes by migrating from the CloudFormation specification to CloudFormation registry resource provider schemas and rewriting over 100 rules. This improves accuracy but may cause templates that previously passed to now fail, or require adjustments to custom rules/configurations.
- gotcha cfn-lint frequently updates its internal CloudFormation schemas to reflect the latest AWS service features and property definitions. While beneficial for up-to-date validation, this can lead to templates that previously passed linting beginning to fail after a `cfn-lint` upgrade, even if the template itself hasn't changed.
- gotcha The `cfn-lint` tool is often used as a command-line interface. There was also an older, deprecated `cfn-lint` npm package (JavaScript-based). Ensure you are installing and using the Python `cfn-lint` for the comprehensive features and active development.
Install
-
pip install cfn-lint -
pip install "cfn-lint[full]" -
pip install "cfn-lint[graph]"
Imports
- CloudFormationLintRule
from cfnlint.rules import CloudFormationLintRule
Quickstart
import subprocess
import os
# Create a dummy CloudFormation template file with an intentional error
template_content = """
AWSTemplateFormatVersion: '2010-09-09'
Resources:
MyS3Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: my-unique-bucket-name
# Intentional error: 'InvalidProperty' is not a valid S3 Bucket property
InvalidProperty: true
"""
template_file = "./my_bad_template.yaml"
with open(template_file, "w") as f:
f.write(template_content)
print(f"Linting {template_file} with cfn-lint...")
try:
# Run cfn-lint as a subprocess
# --format text is default, but explicit for clarity
# --non-zero-exit-code error ensures a non-zero exit if errors are found
result = subprocess.run(
['cfn-lint', template_file, '--non-zero-exit-code', 'error'],
capture_output=True, text=True, check=False
)
print("\n--- cfn-lint Output ---")
print(result.stdout)
if result.stderr:
print("\n--- cfn-lint Errors ---")
print(result.stderr)
if result.returncode != 0:
print(f"\ncfn-lint found issues! Exit Code: {result.returncode}")
else:
print("\ncfn-lint found no issues.")
except FileNotFoundError:
print("Error: cfn-lint command not found. Please ensure it's installed and in your PATH.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
# Clean up the dummy template file
if os.path.exists(template_file):
os.remove(template_file)
print(f"\nCleaned up {template_file}")