DEV Community

Cover image for How do I package data platform components into reusable AWS CDK constructs?
Aniket Abhishek Soni
Aniket Abhishek Soni

Posted on AI-assisted

How do I package data platform components into reusable AWS CDK constructs?

Imagine a scenario where your team manages twenty separate data pipelines. Each developer manually configures their own Amazon S3 buckets, AWS Glue crawlers, and IAM policies. Over time, these configurations drift: some buckets lack encryption, others have overly permissive IAM policies, and the Glue Catalog structures are inconsistent. When a security audit or a storage optimization task arises, you face the manual labor of auditing twenty unique stacks instead of updating a single source of truth.

Packaging your data infrastructure as AWS CDK constructs solves this by enforcing organizational standards through code. By encapsulating infrastructure patterns—such as a "Secured Data Lake Bucket" or a "Standardized ETL Job"—into reusable classes, you ensure that every developer inherits the correct security posture, tagging strategy, and monitoring configuration by default. This scope focuses on creating custom L3 constructs in AWS CDK v2 to standardize the storage, cataloging, and compute layers of a data platform.

Why this matters: Standardizing infrastructure as code prevents configuration drift and ensures that security controls, such as encryption and least-privilege access, are applied consistently across all data assets. By abstracting complexity, you reduce the surface area for human error and streamline the onboarding of new data pipelines.

The requirement

To build a consistent data platform, every data pipeline must satisfy three core infrastructure requirements:

  1. Storage: S3 buckets must be encrypted at rest with AWS KMS, block public access, and enforce TLS for all requests.
  2. Cataloging: Every dataset must have a registered Glue Database and consistent Table metadata to enable discovery and query performance.
  3. Compute: ETL jobs must run with dedicated IAM roles, strictly scoped to the specific bucket and catalog resources they require.
flowchart TD
    construct["Custom CDK Construct"]
    s3["Amazon S3 Bucket"]
    glue["AWS Glue Database"]
    job["AWS Glue ETL Job"]

    construct --> s3
    construct --> glue
    construct --> job
    s3 -.->|managed by| construct
    glue -.->|managed by| construct
    job -.->|uses| s3

Creating the storage construct

Instead of using raw s3.Bucket objects, create a wrapper that enforces security defaults. This ensures that no bucket is created without encryption or public access blocks.

from aws_cdk import (
    aws_s3 as s3,
    aws_kms as kms,
    RemovalPolicy,
    Stack
)
from constructs import Construct

class SecuredDataBucket(Construct):
    def __init__(self, scope: Construct, id: str, **kwargs):
        super().__init__(scope, id)

        # Enforce KMS encryption
        self.key = kms.Key(self, "BucketKey", enable_key_rotation=True)

        self.bucket = s3.Bucket(
            self, "DataBucket",
            encryption=s3.BucketEncryption.KMS,
            encryption_key=self.key,
            block_public_access=s3.BlockPublicAccess.BLOCK_ALL,
            enforce_ssl=True,
            removal_policy=RemovalPolicy.RETAIN
        )
Enter fullscreen mode Exit fullscreen mode

By forcing s3.BucketEncryption.KMS and enforce_ssl=True, you remove the possibility of a developer accidentally creating an unencrypted or public bucket.

Standardizing the catalog and compute

A data platform is useless if the catalog is disorganized. Your construct should automatically pair the S3 bucket with a Glue Database, ensuring that compute jobs are pre-wired to the correct catalog location.

from aws_cdk import (
    aws_glue as glue,
    aws_glue_alpha as glue_alpha
)

class DataPipelineConstruct(Construct):
    def __init__(self, scope: Construct, id: str, database_name: str, **kwargs):
        super().__init__(scope, id)

        # Instantiate the storage construct
        self.storage = SecuredDataBucket(self, "Storage")

        # Create the catalog database
        self.database = glue_alpha.Database(
            self, "GlueDatabase",
            database_name=database_name
        )

        # The compute job (e.g., Glue Job) would be defined here, 
        # referencing self.storage.bucket and self.database.
Enter fullscreen mode Exit fullscreen mode

Applying least-privilege IAM

The most critical aspect of the construct is the IAM role. When you package these components, use the grant_read or grant_write methods provided by the CDK to ensure the job role only has access to the specific resources created within the construct, not the entire account.

# Inside your DataPipelineConstruct
from aws_cdk import aws_iam as iam

self.job_role = iam.Role(
    self, "JobRole",
    assumed_by=iam.ServicePrincipal("glue.amazonaws.com")
)

# Grant access only to the managed bucket and database
self.storage.bucket.grant_read_write(self.job_role)
self.database.grant_to_underlying_resources(self.job_role)
Enter fullscreen mode Exit fullscreen mode

Verify the controls

After deploying your construct, verify that the infrastructure complies with your requirements by using the AWS CLI:

  1. Verify Encryption:
   aws s3api get-bucket-encryption --bucket <your-bucket-name>
Enter fullscreen mode Exit fullscreen mode

Expected output: You should see an ApplyServerSideEncryptionByDefault configuration pointing to your KMS key.

  1. Verify Public Access:
   aws s3api get-public-access-block --bucket <your-bucket-name>
Enter fullscreen mode Exit fullscreen mode

Expected output: All fields (BlockPublicAcls, IgnorePublicAcls, BlockPublicPolicy, RestrictPublicBuckets) should be true.

  1. Verify IAM scope: Check the IAM policy attached to your job role in the AWS Management Console to ensure it contains only s3:ListBucket and s3:GetObject/PutObject actions restricted to the specific bucket ARN.

What this doesn't cover

These constructs simplify infrastructure provisioning but do not replace data governance. This approach does not:

  • Validate data schema: You still need tools like AWS Glue DataBrew or custom PySpark validation logic to ensure the data within the bucket meets your quality standards.
  • Manage cross-account access: If your data platform spans multiple AWS accounts, you need to implement Resource-Based Policies (Bucket Policies) and AWS Lake Formation cross-account sharing, which are separate from simple resource provisioning.
  • Optimize for performance: While the construct ensures encryption and security, it does not dictate your partitioning strategy or file formats (e.g., Parquet vs. CSV).

Clean up

To avoid ongoing costs for the resources created during your testing:

  1. Identify the CloudFormation stack created by your CDK app.
  2. Run the destruction command:
   cdk destroy --all
Enter fullscreen mode Exit fullscreen mode
  1. Manually empty the S3 buckets if they were created with RemovalPolicy.RETAIN (which is recommended for production data), as CloudFormation will not delete buckets that contain objects.

Conclusion

Packaging your data platform as AWS CDK constructs shifts your role from managing individual resources to managing architectural patterns. By creating "opinionated" constructs for storage, cataloging, and compute, you enforce security and operational standards by design rather than by policy document. Your next step is to publish these constructs to an internal CodeArtifact repository, allowing other teams to consume your vetted infrastructure patterns while maintaining a centralized update path for security patches.

References

About the examples: automated checks confirmed that the Python blocks parse and that 2 AWS CLI commands match the AWS service API models (operation and parameter names). The examples have not been run end to end, so test them in a non-production environment before relying on them.

Cover photo by Brecht Corbeel on Unsplash.


This article was drafted with AI assistance and is intended for technical review and fact-checking before publication.

Top comments (0)