aws-cdk-local

repository·main·Indexed 43 days ago

https://github.com/localstack/aws-cdk-local

A thin wrapper script (cdklocal) and CDK Toolkit for use with LocalStack. It applies runtime patching to the AWS Cloud Development Kit (CDK) to redirect requests to LocalStack's local APIs instead of real AWS services, supporting standard commands like deploy, synth, and diff. Version 3.0.4 includes features such as local Lambda code mounting via LAMBDA_MOUNT_CODE and automatic path-style S3 URL support for remote endpoints.

Tokens
2.7K
Snippets
10
Records
14
Agent score
54%

What's inside aws-cdk-local

  1. Use path-style S3 URLs for remote endpoints

    main

    When using CDK >= 2.177.0 with remote LocalStack endpoints (e.g., *.sandbox.localstack.cloud), asset uploads to S3 require path-style URLs because wildcard TLS certificates do not cover virtual-hosted-style bucket addresses (e.g., <bucket>.abc.sandbox.localstack.cloud).

    cdklocal automatically enables path-style S3 if it detects a .sandbox. hostname in AWS_ENDPOINT_URL. You can also force this behavior manually using AWS_S3_FORCE_PATH_STYLE=1.

  2. Install cdklocal and AWS CDK

    main

    To use the AWS CDK with LocalStack, you must install both the aws-cdk-local wrapper and the standard aws-cdk library. Since version 1.65.2, aws-cdk must be installed manually to allow for decoupled version management.

    Use the following command to install both globally via npm:

    $ npm install -g aws-cdk-local aws-cdk
  3. Deploy a sample app with cdklocal

    main

    To verify your installation, you can generate and deploy a sample application.

    1. Ensure LocalStack is running: localstack start.
    2. Initialize a sample app using cdklocal init.
    3. Deploy the app using cdklocal deploy.
    4. Verify resources using awslocal (from the awscli-local package).
    # 1. Setup directory and initialize sample app
    $ mkdir /tmp/test; cd /tmp/test
    $ cdklocal init sample-app --language=javascript
    
    # 2. Ensure LocalStack is running
    $ localstack start
    
    # 3. Deploy
    $ cdklocal deploy
    
    # 4. Inspect resources (requires awslocal)
    $ awslocal sns list-topics
  4. Configure cdklocal environment variables

    main

    You can control how cdklocal interacts with LocalStack using several environment variables.

    Note for CDK >= 2.177.0: cdklocal automatically sanitizes the environment by removing variables like AWS_PROFILE to prevent conflicts. If you need to pass specific AWS configuration variables (like AWS_REGION) to the underlying CDK command, you must use the AWS_ENVAR_ALLOWLIST variable.

    # Example: Allowing specific variables to pass through to the CDK command
    $ AWS_ENVAR_ALLOWLIST=AWS_REGION,AWS_DEFAULT_REGION AWS_DEFAULT_REGION=eu-central-1 AWS_REGION=eu-central-1 cdklocal deploy
  5. Enable local Lambda code mounting with LAMBDA_MOUNT_CODE

    main

    When LAMBDA_MOUNT_CODE=1 is set, cdklocal changes how Lambda assets are handled during synth and deploy:

    1. Symlinking: It creates symlinks in cdk.out/asset.lambda.<function_name> pointing to your local source code.
    2. Parameter Injection: It modifies the CloudFormation template parameters (specifically those containing S3VersionKey) to point to the local file path instead of an S3 location.
    3. Skipping Uploads: It intercepts the FileAssetHandler.publish method to skip the actual upload of zipped Lambda assets to S3, as they are intended to be mounted locally.

    This is particularly useful for rapid iteration on Lambda function logic.

    export LAMBDA_MOUNT_CODE=1
    cdklocal deploy
  6. Use cdklocal to run AWS CDK commands against LocalStack

    main

    cdklocal is a wrapper around the standard AWS CDK CLI. It intercepts CDK calls and redirects them to a LocalStack instance by patching the underlying SDK providers, credentials, and toolkit information. This allows you to use standard CDK commands (like deploy, synth, diff) while targeting LocalStack instead of real AWS services.

    To use it, ensure you have aws-cdk installed in your environment, then replace the cdk command with cdklocal.

    # Instead of:
    cdk deploy
    
    # Use:
    cdklocal deploy
  7. Resolve Mac OS MODULE_NOT_FOUND error

    main

    If you installed AWS CDK via Homebrew on macOS, cdklocal might fail with a MODULE_NOT_FOUND error. To fix this, you must set the NODE_PATH environment variable to point to the AWS CDK node_modules directory within the Homebrew Cellar.

    Replace <CDK_VERSION> with your specific installed version:

    $ export NODE_PATH=$NODE_PATH:/opt/homebrew/Cellar/aws-cdk/<CDK_VERSION>/libexec/lib/node_modules
  8. Configure cdklocal via environment variables

    main

    You can customize how cdklocal connects to LocalStack and handles assets using the following environment variables:

    VariableDescription
    AWS_ENDPOINT_URLOverrides the default LocalStack endpoint. If not set, it defaults to http://localhost:4566 (or 127.0.0.1 on some macOS systems).
    LOCALSTACK_HOSTNAMESets the hostname for LocalStack (defaults to localhost).
    AWS_S3_FORCE_PATH_STYLEIf set to 1 (or any truthy value), forces S3 to use path-style URLs (e.g., http://localhost:4566/bucket instead of http://bucket.localhost:4566).
    LAMBDA_MOUNT_CODEIf set to 1, enables local Lambda code mounting. This allows you to symlink local Lambda assets instead of uploading them, facilitating faster development/hot-reloading.
    BUCKET_MARKER_LOCALUsed in conjunction with LAMBDA_MOUNT_CODE. Defines the marker used in S3 bucket parameters to identify local assets. Defaults to __local__.
    AWS_ENVAR_ALLOWLISTA list of AWS environment variables to allow through the patching mechanism.
    AWS_ACCESS_KEY_IDOverrides the default test access key.
    AWS_SECRET_ACCESS_KEYOverrides the default test secret key.
  9. Reference: cdklocal configuration variables

    main

    The following environment variables are available for configuring cdklocal behavior:

    * AWS_ENDPOINT_URL: The endpoint URL to connect to (combination of USE_SSL/LOCALSTACK_HOSTNAME/EDGE_PORT below)
    * AWS_ENDPOINT_URL_S3: The endpoint URL to connect to (combination of USE_SSL/LOCALSTACK_HOSTNAME/EDGE_PORT below) for S3 requests
    * AWS_ENVAR_ALLOWLIST: Allow specific AWS_* environment variables to be used by the CDK
    * AWS_S3_FORCE_PATH_STYLE: Force path-style S3 URLs (CDK >= 2.177.0 only). Automatically enabled when AWS_ENDPOINT_URL hostname contains .sandbox.
    * EDGE_PORT (deprecated): Port under which LocalStack edge service is accessible (default: 4566)
    * LOCALSTACK_HOSTNAME (deprecated): Target host under which LocalStack edge service is accessible (default: localhost)
    * USE_SSL (deprecated): Whether to use SSL to connect to the LocalStack endpoint, i.e., connect via HTTPS.
    * LAMBDA_MOUNT_CODE: Whether to use local Lambda code mounting (via setting __local__ S3 bucket name). Note: may require CDK version <2.14.0 to be fully functional.
    * BUCKET_MARKER_LOCAL: Magic S3 bucket name for Lambda mount and hot reloading (default: __local__, will default to hot-reload in a future release)
  10. Configure the environment for aws-cdk-local

    main

    Use configureEnvironment to prepare the process environment for AWS CDK to work with LocalStack. This function ensures that necessary AWS credentials, regions, and endpoint URLs are set correctly while stripping out potentially conflicting AWS environment variables.

    Key Behaviors:

    • Endpoint Configuration: It explicitly sets AWS_ENDPOINT_URL and AWS_ENDPOINT_URL_S3 using localhost.localstack.cloud to ensure subdomains resolve correctly, as the CDK requires this for S3 requests.
    • Credential Defaults: If not already present, it sets AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY to "test".
    • Region Defaults: If not already present, it sets AWS_REGION and AWS_DEFAULT_REGION to "us-east-1".
    • Environment Cleaning: It removes AWS-prefixed environment variables (e.g., AWS_PROFILE, AWS_CONFIG_FILE) unless they are explicitly included in the allowListStr or are part of the AWS_ENDPOINT_URL family.
    • Validation: If AWS_ENDPOINT_URL is provided but AWS_ENDPOINT_URL_S3 is missing, it throws an EnvironmentMisconfigurationError to prevent incorrect S3 request parsing.
    const { configureEnvironment } = require('aws-cdk-local');
    
    // Example: Configure environment and allow 'AWS_PROFILE' to persist
    configureEnvironment(process.env, 'AWS_PROFILE');
  11. Check truthy environment variables with isEnvTrue

    main

    The isEnvTrue utility function checks if a specific environment variable is set to a truthy string value. A value is considered true if it is exactly "1" or "true".

    const { isEnvTrue } = require('aws-cdk-local');
    
    // Returns true if process.env.USE_SSL is "1" or "true"
    const useSsl = isEnvTrue("USE_SSL");
  12. Reference: aws-cdk-local exported constants

    main

    The following constants are exported by the package:

    • EDGE_PORT: The port used to access the LocalStack edge proxy. Defaults to 4566 or the value of the EDGE_PORT environment variable.
    • PROTOCOL: The network protocol used for endpoints. It is "https" if the USE_SSL environment variable is set to "1" or "true", otherwise it defaults to "http".