Table of Contents
Example verification
AWS CDK Construction Example
Multiple verifications
Updated AWS CDK construction example
AWS CDK Stack Verification
AWS CDK Stack Example
Built-in verification
Conclusion
Home Backend Development Python Tutorial AWS CDK Validation in Python

AWS CDK Validation in Python

Jan 20, 2025 pm 04:25 PM

AWS CDK Validation in Python

The AWS CDK application life cycle includes verification steps, which are explained in the CDK application synthesis chapter of the official documentation:

All constructs that implement the validate method can be self-validated to ensure they are in a state for correct deployment. Any validation failures that occur at this stage will be notified to you. In general, we recommend performing validation as quickly as possible (usually as soon as some input is obtained) and throwing exceptions as quickly as possible. Performing verification early improves reliability because stack traces will be more accurate and ensures your code can safely continue execution.

While there are some excellent articles on how to handle AWS CDK validation in TypeScript (linked below), I couldn't find a corresponding Python example. After creating some validations in Python, the following example complements the examples in these articles.

  • Validation checks in AWS CDK constructs
  • Use AWS CDK for validation (addValidation)

The following examples were developed using AWS CDK v2.176.0 and Python 3.13.1.

Example verification

The implementation of validation is done using the validate method which returns a list of error messages. If the list is empty, there are no errors; multiple entries correspond to different validation checks for which this validation failed. The validation logic is encapsulated in a class annotated with @jsii.implements(IValidation), indicating that it is the correct type for validation. In this example, there is a check that the Amazon S3 bucket passed to verify uses a custom AWS KMS key, which provides more control over the encryption process compared to the default encryption used by Amazon S3.

@jsii.implements(IValidation)
class KodlotS3KmsValidator:
    """检查S3存储桶是否使用自定义KMS密钥加密。"""

    def __init__(self, s3_bucket: s3.Bucket):
        self.s3_bucket = s3_bucket

    def validate(self) -> List[str]:
        error_messages: List[str] = []
        if self.s3_bucket.encryption_key is None:
            error_messages.append(f"存储桶必须使用自定义KMS密钥加密")
        return error_messages
Copy after login
Copy after login

AWS CDK Construction Example

This is a basic example of an AWS CDK construct that adds a single validation using the add_validation method of the constructor node in the scope tree. There was a bug during the implementation where a custom AWS KMS key was created but not passed to the encryption_key parameter of the Amazon S3 bucket construct.

class KodlotS3Bucket(Construct):
    """带有验证的S3存储桶。"""

    def __init__(self, scope: Construct, construct_id: str, bucket_name: str) -> None:
        super().__init__(scope, construct_id)

        s3_kms_key = kms.Key(self, f"KodlotS3KmsKey{bucket_name.title()}")
        self.s3_bucket = s3.Bucket(
            self,
            f"KodlotS3{bucket_name.title()}",
            bucket_name=bucket_name,
            encryption_key=None,
        )

        self.node.add_validation(KodlotS3KmsValidator(self.s3_bucket))
Copy after login
Copy after login

This type of error is easily overlooked, which is where validation comes into play. Running a CDK composition or deployment using this example will result in the following error:

<code>RuntimeError: Error: 验证失败,错误如下:
  [KodlotS3Stack/KodlotBucket1] 存储桶必须使用自定义KMS密钥加密</code>
Copy after login
Copy after login

Multiple verifications

It is possible to have multiple validators testing different aspects of our configuration, and they can be reused for different constructs if we find common patterns like this. In this example, a validation check is added to ensure that the Amazon S3 bucket is not accidentally configured for static website hosting, in which case this would be an error.

@jsii.implements(IValidation)
class KodlotS3NotWebsiteValidator:
    """检查S3存储桶未配置为静态网站托管。"""

    def __init__(self, s3_bucket: s3.Bucket):
        self.s3_bucket = s3_bucket

    def validate(self) -> List[str]:
        error_messages: List[str] = []
        if self.s3_bucket.is_website:
            error_messages.append(f"存储桶不能用于静态网站托管")
        return error_messages
Copy after login
Copy after login

Updated AWS CDK construction example

To use an additional validator to check whether website hosting is configured for an Amazon S3 bucket, update the sample CDK construct as shown below. This time, the original error of not passing a custom AWS KMS key is retained. Now, in addition, website_index_document is incorrectly passed to the Amazon S3 bucket construct, indicating that it will be used for static website hosting.

@jsii.implements(IValidation)
class KodlotS3KmsValidator:
    """检查S3存储桶是否使用自定义KMS密钥加密。"""

    def __init__(self, s3_bucket: s3.Bucket):
        self.s3_bucket = s3_bucket

    def validate(self) -> List[str]:
        error_messages: List[str] = []
        if self.s3_bucket.encryption_key is None:
            error_messages.append(f"存储桶必须使用自定义KMS密钥加密")
        return error_messages
Copy after login
Copy after login

This time, we have two different issues with our Amazon S3 bucket, both of which are reported by the verification mechanism as shown below. Running a CDK composition or deployment using this example will result in the following error:

class KodlotS3Bucket(Construct):
    """带有验证的S3存储桶。"""

    def __init__(self, scope: Construct, construct_id: str, bucket_name: str) -> None:
        super().__init__(scope, construct_id)

        s3_kms_key = kms.Key(self, f"KodlotS3KmsKey{bucket_name.title()}")
        self.s3_bucket = s3.Bucket(
            self,
            f"KodlotS3{bucket_name.title()}",
            bucket_name=bucket_name,
            encryption_key=None,
        )

        self.node.add_validation(KodlotS3KmsValidator(self.s3_bucket))
Copy after login
Copy after login

This is very powerful because we can collect different configuration issues in the cloud infrastructure and resolve them all without having to rerun and fix them again and again.

AWS CDK Stack Verification

It’s worth remembering that validation is not limited to AWS CDK constructs and can be added to the AWS CDK stack level as well. Here we can for example check if a given stack does not contain unwanted resources. If our requirement is that the stack should not contain any AWS Lambda resources, then we can simulate that requirement using the validation described below. Using the child of a node construct, you can use Python's built-in isinstance function to check whether any resource is an instance of an AWS CDK function.

<code>RuntimeError: Error: 验证失败,错误如下:
  [KodlotS3Stack/KodlotBucket1] 存储桶必须使用自定义KMS密钥加密</code>
Copy after login
Copy after login

AWS CDK Stack Example

To add validation to the stack we use the same add_validation method as the constructor. Since KodlotS3Stack is identified as a stack that must not contain any AWS Lambda functions, it is a good place to test the validation of the example stack. If an error occurs during development, such as the one described below, where a developer defines an AWS Lambda function resource, the verification will take effect.

@jsii.implements(IValidation)
class KodlotS3NotWebsiteValidator:
    """检查S3存储桶未配置为静态网站托管。"""

    def __init__(self, s3_bucket: s3.Bucket):
        self.s3_bucket = s3_bucket

    def validate(self) -> List[str]:
        error_messages: List[str] = []
        if self.s3_bucket.is_website:
            error_messages.append(f"存储桶不能用于静态网站托管")
        return error_messages
Copy after login
Copy after login

Running the CDK composition or deployment of this example will result in the following error:

class KodlotS3Bucket(Construct):
    """带有验证的S3存储桶。"""

    def __init__(self, scope: Construct, construct_id: str, bucket_name: str) -> None:
        super().__init__(scope, construct_id)

        s3_kms_key = kms.Key(self, f"KodlotS3KmsKey{bucket_name.title()}")
        self.s3_bucket = s3.Bucket(
            self,
            f"KodlotS3{bucket_name.title()}",
            bucket_name=bucket_name,
            encryption_key=None,
            website_index_document="index.html",
        )

        self.node.add_validation(KodlotS3KmsValidator(self.s3_bucket))
        self.node.add_validation(KodlotS3NotWebsiteValidator(self.s3_bucket))
Copy after login

Built-in verification

It is also worth checking whether the AWS CDK already provides checks for certain aspects of our cloud infrastructure. In the context of Amazon S3, it turns out that if we configure the bucket name to k1, resulting in an illegal name length, we get the following built-in error:

<code>RuntimeError: Error: 验证失败,错误如下:
  [KodlotS3Stack/KodlotBucket1] 存储桶必须使用自定义KMS密钥加密
  [KodlotS3Stack/KodlotBucket1] 存储桶不能用于静态网站托管</code>
Copy after login

Similarly, if we configure the bucket name as k_1, resulting in an illegal underscore character in it, the following built-in error will occur:

@jsii.implements(IValidation)
class KodlotNoLambdaInStackValidator:
    """检查给定堆栈中未定义任何Lambda函数。"""

    def __init__(self, stack: cdk.Stack):
        self.stack = stack

    def validate(self) -> List[str]:
        error_messages: List[str] = []
        for construct in self.stack.node.children:
            if isinstance(construct, _lambda.Function):
                error_messages.append(f"堆栈不能包含任何Lambda函数")
        return error_messages
Copy after login

Conclusion

AWS CDK validation is a useful mechanism that developers can use in conjunction with unit and integration tests to ensure the overall quality of the cloud computing infrastructure. Being able to catch common misconfigurations and define standards will lead to reusable validations that can be shared between different components. Validation can be added at different levels defined by AWS CDK, including AWS CDK constructs and AWS CDK stacks. It's good to see that the AWS CDK has captured some common validations, as they are fundamental to various cloud services and resources and should always be checked, reducing the likelihood of encountering deployment errors in a production environment.

The code blocks are preserved and the image is referenced correctly. The overall structure and meaning remain the same, while the wording is altered for a more natural flow and to avoid direct repetition.

The above is the detailed content of AWS CDK Validation in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles