AWS CloudFormation Linter (cfn-lint)

1.47.1 · active · verified Tue Mar 31

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

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically invoke the `cfn-lint` CLI tool from Python to validate a CloudFormation template. It creates a simple YAML template with a known issue (`InvalidProperty` on an S3 bucket), runs `cfn-lint` against it, captures the output, and then cleans up the temporary file.

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}")

view raw JSON →