CDK Nag

2.37.55 · active · verified Fri Apr 10

cdk-nag is an open-source library for the AWS Cloud Development Kit (CDK) that checks CDK applications for security and compliance best practices. It functions as a linter for Infrastructure as Code, leveraging CDK Aspects to validate constructs against various rule packs like AWS Solutions, HIPAA, NIST, and PCI DSS. The library helps identify issues such as unencrypted S3 buckets, overly permissive IAM policies, and public databases before deployment. It is currently at version 2.37.55 and actively maintained with a regular release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to integrate `cdk-nag` into a Python CDK application. It creates a simple S3 bucket that would typically trigger AWS Solutions best practice warnings. It then shows how to apply the `AwsSolutionsChecks` to the entire application and how to add a suppression for a specific rule on a resource, including a mandatory reason for the suppression. Run `cdk synth` after adding this code to see the nag findings.

import os
from aws_cdk import App, Stack, Aspects, aws_s3 as s3
from constructs import Construct
from cdk_nag import AwsSolutionsChecks, NagSuppressions

class MyNaggedStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # An S3 bucket that will likely trigger some AwsSolutions nags
        # for missing logging, encryption, and public access blocks.
        my_bucket = s3.Bucket(self, "MyInsecureBucket")

        # Suppress a specific finding on the bucket with a clear reason
        # This suppression is for demonstration; always address findings first.
        NagSuppressions.add_resource_suppressions(
            my_bucket,
            [
                {
                    "id": "AwsSolutions-S1",
                    "reason": "This is a demonstration bucket; access logging is not critical for this specific example."
                }
            ]
        )

app = App()

# Apply AWS Solutions Checks to the entire app
Aspects.of(app).add(AwsSolutionsChecks(verbose=True))

MyNaggedStack(app, "CdkNagDemoStack")

app.synth()

view raw JSON →