AWS CDK Asset AWS CLI v1

2.2.274 · active · verified Thu Apr 09

The `aws-cdk-asset-awscli-v1` library provides the AWS CLI (version 1) as a Lambda Layer asset for use within AWS CDK applications. It allows Lambda functions to execute AWS CLI commands directly. This package is maintained by cdklabs and receives updates in sync with the broader AWS CDK ecosystem.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create an `AwsCliLayer` and attach it to a Lambda function. The Lambda's code then executes a simple AWS CLI command (`aws s3 ls`). Remember to grant the Lambda's execution role the necessary IAM permissions for any AWS CLI commands it will run.

import os
from aws_cdk import (
    App,
    Stack,
    aws_lambda as lambda_,
)
from aws_cdk_asset_awscli_v1 import AwsCliLayer

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

        # Create the AWS CLI v1 Lambda Layer
        aws_cli_layer = AwsCliLayer(self, "AwsCliV1Layer")

        # Define a Lambda function that uses the layer
        lambda_function = lambda_.Function(
            self,
            "MyLambdaWithAwsCli",
            runtime=lambda_.Runtime.PYTHON_3_9, # Ensure compatibility with asset's Python requirement
            handler="index.handler",
            code=lambda_.Code.from_inline(
                """
import json
import subprocess

def handler(event, context):
    try:
        # Example: run 'aws s3 ls' to list S3 buckets
        # The Lambda's IAM role must have s3:ListBucket permissions.
        result = subprocess.run(['aws', 's3', 'ls'], capture_output=True, text=True, check=True)
        return {
            'statusCode': 200,
            'body': json.dumps({'message': 'AWS CLI executed successfully', 'output': result.stdout})
        }
    except subprocess.CalledProcessError as e:
        return {
            'statusCode': 500,
            'body': json.dumps({'error': f"AWS CLI error: {e.stderr}"})
        }
    except Exception as e:
        return {
            'statusCode': 500,
            'body': json.dumps({'error': str(e)})
        }
                """
            ),
            layers=[aws_cli_layer],
            # Add IAM permissions required for CLI commands, e.g., s3:ListBucket for 'aws s3 ls'
            # For a production setup, consider defining a more granular policy.
            # lambda_function.add_to_role_policy(iam.PolicyStatement(actions=["s3:ListBucket"], resources=["arn:aws:s3:::*"]))
        )

app = App()
MyAwsCliStack(app, "MyAwsCliStack")
app.synth()

view raw JSON →