To add on to the previous article that described how to import an Amazon Lex Bot with CDK, I have created a CDK Construct that you can import and use in your own CDK projects.
To add this to your CDK project, simply import the Construct:
yarn add cdk-lex-zip-import
Within your CDK:
const bot = new lexupload.ImportBot(this, 'lexBot', { sourceDirectory: './resources/LexBot', lexRoleArn: lexRole.roleArn, });
The sourceDirectory
must include a file named LexBot.zip
. This file will be uploaded to an S3 Bucket and then imported using a Lambda backed Custom Resource.
Additionally, a Resource Policy can be applied to the Alias once it is imported.
bot.addResourcePolicy(resourceArn, policy);
A complete example might look like this:
import { Stack, StackProps } from 'aws-cdk-lib'; import * as iam from 'aws-cdk-lib/aws-iam'; import * as lexupload from 'cdk-lex-zip-import'; import { Construct } from 'constructs'; export class MyStack extends Stack { constructor(scope: Construct, id: string, props: StackProps = {}) { super(scope, id, props); const lexRole = new iam.Role(this, 'lexRole', { assumedBy: new iam.ServicePrincipal('lex.amazonaws.com'), inlinePolicies: { ['lexPolicy']: new iam.PolicyDocument({ statements: [ new iam.PolicyStatement({ resources: ['*'], actions: ['polly:SynthesizeSpeech', 'comprehend:DetectSentiment'], }), ], }), }, }); const bot = new lexupload.ImportBot(this, 'lexBot', { sourceDirectory: './resources/LexBot', lexRoleArn: lexRole.roleArn, }); const resourceArn = `arn:aws:lex:${this.region}:${this.account}:bot-alias/${bot.botId}/${bot.botAliasId}`; const policy = { Version: '2012-10-17', Statement: [ { Sid: 'AllowChimePstnAudioUseBot', Effect: 'Allow', Principal: { Service: 'voiceconnector.chime.amazonaws.com' }, Action: 'lex:StartConversation', Resource: resourceArn, Condition: { StringEquals: { 'AWS:SourceAccount': `${this.account}` }, ArnEquals: { 'AWS:SourceArn': `arn:aws:voiceconnector:us-east-1:${this.account}:*`, }, }, }, ], }; bot.addResourcePolicy(resourceArn, policy); } }
For more information or to contribute, please see the GitHub repo.