--- title: "手动创建lambda函数" draft: false chapter: false hidden: true --- ## 配置 Lambda Execution Role 1. [点击此处打开IAM 控制台](https://console.aws.amazon.com/iam/home?region=us-east-1#/roles), 选择 **Roles** 1. 点击 **Create Role** 1. 在 Choose the service that will use this role 中, 选择 **Lambda** 1. 点击 **Next: Permissions**, **Next: Tags**, **Next: Review** 1. 在 Review 页面, 对于**Role name** 输入 `alexa-lambda-role`, 并且点击 **Create role** 1. 选择刚才创建的 `alexa-lambda-role`, 在 **Permissions** 中, 选择 **Add inline policy** 1. 在 Create Policy 页面, 选择 **JSON**, 复制并黏贴如下的 Policy. 请务必更改 ``. 到 DynamoDB 的控制台中确认表的名称. 如何您按照[创建设备绑定程序]({{< ref "1.build-device-ui.zh.md" >}})执行, 一个 DynamoDB 表已经被创建. 以下的 Policy 授权 Lambda 可以读取设备表中的数据,并且将运行时产生的日志信息输出到 CloudWatch Logs. ```json { "Version": "2012-10-17", "Statement": [ { "Action": [ "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": [ "*" ], "Effect": "Allow" }, { "Action": [ "dynamodb:Query" ], "Resource": [ "arn:aws:dynamodb:*:*:table//index/ByUsernameThingName" ], "Effect": "Allow" }, { "Action": [ "iot:UpdateThingShadow" ], "Resource": [ "*" ], "Effect": "Allow" } ] } ``` 1. 点击 **Review Policy** 1. 在 **Name** 字段, 输入一个名称 1. 点击 **Create Policy** ## 创建 Lambda 1. 打开 [Lambda 控制台](https://console.aws.amazon.com/lambda/home?region=us-east-1), 点击 **Create function** 1. 选择 **Select Author from scratch**, 并且输入以下信息: - Name: Lambda 方法的名称 - Runtime: **Node.js 10.x** - Role: 选择在[配置 Lambda Execution Role](#配置-lambda-execution-role)中创建的角色 ![](/images/smart-home/create-lambda-1.png) 1. 点击 **Create Function**. Lambda 方法已经创建,并且会被自动导航到 **Configuration** 1. 在 **Configuration** designer 中, 在 **Add triggers** 下, 选择 **Alexa Smart Home trigger** 1. 在 **Configure triggers** 中, 输入 **Skill ID**,这个 Skill ID 可以在 Alexa Developer 控制台中找到。 1. 保持 **Enable trigger** 选中. 这个选项,让 Lambda 可以接受来自 Amazon Alexa 的指令。如果您关闭这个选项,Lambda 将无法收到指令。 1. 点击 **Add**,然后选择 **Save** ## 打包上传代码 1. 首先,您需要下载这个 [GitHub Repo](https://github.com/aws-samples/aws-alexa-workshop-smarthome), 进入您的 Cloud9 环境根目录, 在 terminal 中输入 ```shell git clone https://github.com/aws-samples/aws-alexa-workshop-smarthome cd aws-alexa-workshop-smarthome ``` 1. 编辑 `config.json` 文件, 您可以在 AWS 控制台,和 Alexa Developer 控制台中找到相关的信息 1. 运行 `npm install --production` 安装依赖 1. 将 `index.js`, `auth.js`, `config.json`, `alexa/` and `node_modules/` 进行打包 这些文件/文件夹必须位于 ZIP 文件的根目录下 ``` zip -q -r lambda.zip index.js auth.js config.json alexa/ node_modules/ ``` ![](/images/smart-home/lambda-file-structure.png) 1. 将这个 ZIP 文件下载到本地 1. 打开 AWS Lambda 控制台,选择刚才创建的 Lambda 方法 1. 在 **Function Code** 中,在 **Code entry type** 中选择 **Upload a .zip file** 1. 选择 **Upload** 来上传 ZIP 文件 1. 点击右上角的 **Save** 按钮