编辑: CloudFormation 对 AWS Lex 的支持现已推出,请参阅 Wesley Cheek 的回答。以下是我的原始答案,它解决了使用自定义资源缺乏 CloudFormation 支持的问题。
有!虽然可能有点麻烦,但使用自定义资源是完全可能的。
自定义资源通过定义处理自定义资源的创建和删除事件的 lambda 来工作。由于可以使用 AWS API 创建和删除 AWS Lex 机器人,因此我们可以让 lambda 在创建或销毁资源时执行此操作。
这是我用 TS/JS 编写的一个简单示例:
CDK 代码(打字稿):
import * as path from 'path';
import * as cdk from '@aws-cdk/core';
import * as iam from '@aws-cdk/aws-iam';
import * as logs from '@aws-cdk/aws-logs';
import * as lambda from '@aws-cdk/aws-lambda';
import * as cr from '@aws-cdk/custom-resources';
export class CustomResourceExample extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// Lambda that will handle the different cloudformation resource events
const lexBotResourceHandler = new lambda.Function(this, 'LexBotResourceHandler', {
code: lambda.Code.fromAsset(path.join(__dirname, 'lambdas')),
handler: 'lexBotResourceHandler.handler',
runtime: lambda.Runtime.NODEJS_14_X,
});
lexBotResourceHandler.addToRolePolicy(new iam.PolicyStatement({
resources: ['*'],
actions: ['lex:PutBot', 'lex:DeleteBot']
}))
// Custom resource provider, specifies how the custom resources should be created
const lexBotResourceProvider = new cr.Provider(this, 'LexBotResourceProvider', {
onEventHandler: lexBotResourceHandler,
logRetention: logs.RetentionDays.ONE_DAY // Default is to keep forever
});
// The custom resource, creating one of these will invoke the handler and create the bot
new cdk.CustomResource(this, 'ExampleLexBot', {
serviceToken: lexBotResourceProvider.serviceToken,
// These options will be passed down to the lambda
properties: {
locale: 'en-US',
childDirected: false
}
})
}
}
Run Code Online (Sandbox Code Playgroud)
Lambda 代码 (JavaScript):
const AWS = require('aws-sdk');
const Lex = new AWS.LexModelBuildingService();
const onCreate = async (event) => {
await Lex.putBot({
name: event.LogicalResourceId,
locale: event.ResourceProperties.locale,
childDirected: Boolean(event.ResourceProperties.childDirected)
}).promise();
};
const onUpdate = async (event) => {
// TODO: Not implemented
};
const onDelete = async (event) => {
await Lex.deleteBot({
name: event.LogicalResourceId
}).promise();
};
exports.handler = async (event) => {
switch (event.RequestType) {
case 'Create':
await onCreate(event);
break;
case 'Update':
await onUpdate(event);
break;
case 'Delete':
await onDelete(event);
break;
}
};
Run Code Online (Sandbox Code Playgroud)
我承认这是一个非常简单的示例,但希望它足以让您或任何人开始阅读,并了解如何通过添加更多选项和更多自定义资源(例如意图)来构建它。
| 归档时间: |
|
| 查看次数: |
405 次 |
| 最近记录: |