AWS CDK Asset AWS CLI v1
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
- gotcha This package specifically provides AWS CLI v1. If you require AWS CLI v2, you MUST use the `aws-cdk-asset-awscli-v2` package instead. Mixing versions or mistakenly assuming v2 can lead to unexpected behavior or missing features.
- gotcha The AWS CLI layer is substantial in size (around 50MB unzipped). This can contribute to increased Lambda cold start times and potentially push your deployment package size close to Lambda limits. Only include it if truly necessary.
- gotcha This asset package has specific Python runtime requirements (e.g., `~=3.9` as per PyPI). Using a Lambda function with an incompatible Python runtime (e.g., Python 3.7 or Python 3.12 if not supported) may lead to runtime errors when the CLI attempts to execute.
Install
-
pip install aws-cdk-asset-awscli-v1 aws-cdk-lib
Imports
- AwsCliLayer
from aws_cdk_asset_awscli_v1 import AwsCliLayer
Quickstart
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()