使用 cdk 的内联 lambda 函数

inline lambda function using cdk

此代码按预期工作,我可以创建 cloudformation 模板。但我需要内嵌函数。此示例代码会将文件上传到 S3,我不想使用 S3。

# cat mylambda/hello.py
import json

def handler(event, context):
    print('request: {}'.format(json.dumps(event)))
    return {
        'statusCode': 200,
        'headers': {
            'Content-Type': 'text/plain'
        },
        'body': 'Hello, CDK! You have hit {}\n'.format(event['path'])
    }
# cat app.py
#!/usr/bin/env python3
from aws_cdk import core
from hello.hello_stack import MyStack

app = core.App()
MyStack(app, "hello-cdk-1", env={'region': 'us-east-2'})
MyStack(app, "hello-cdk-2", env={'region': 'us-west-2'})

app.synth()
# cat hello/hello_stack.py
from aws_cdk import (
    core,
    aws_lambda as _lambda,
)

class MyStack(core.Stack):

    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Defines an AWS Lambda resource
        my_lambda = _lambda.Function(
            self, 'HelloHandler',
            runtime=_lambda.Runtime.PYTHON_3_7,
            code=_lambda.Code.asset('mylambda'),
            handler='hello.handler',
        )

这是一个可以使用 cdk 部署的内联 lambda 函数的示例

git clone https://github.com/aws-samples/aws-cdk-examples.git

mkdir lambda-cron1
cd lambda-cron1

cdk init --language python

cp /tmp/aws-cdk-examples/python/lambda-cron/* .

pip install -r requirements.txt

export AWS_DEFAULT_REGION=us-east-1
export AWS_ACCESS_KEY_ID=xxx
export AWS_SECRET_ACCESS_KEY=xxx

cdk ls

cdk synth LambdaCronExample  > a2.txt

cdk deploy  LambdaCronExample