SAM 调用不会采用本地环境变量
Posted
技术标签:
【中文标题】SAM 调用不会采用本地环境变量【英文标题】:SAM invoke won't take local env vars 【发布时间】:2022-01-24 05:50:36 【问题描述】:我有一个带有基本端点的示例 SAM 应用程序。我只想通过以下方式在本地运行它:
sam local invoke -e events/event-post-item.json putItemFunction --profile myprofile -n local.json
local.json
如下:
"getAllItems":
"SAMPLE_TABLE": "mywebservices-SampleTable-1BS18COYN2SHV"
,
"getById":
"SAMPLE_TABLE": "mywebservices-SampleTable-1BS18COYN2SHV"
,
"putItem":
"SAMPLE_TABLE": "mywebservices-SampleTable-1BS18COYN2SHV"
下面是putItemFunction
的代码
// Create clients and set shared const values outside of the handler
// Create a DocumentClient that represents the query to add an item
const dynamodb = require('aws-sdk/clients/dynamodb');
const docClient = new dynamodb.DocumentClient();
// Get the DynamoDB table name from environment variables
const tableName = process.env.SAMPLE_TABLE;
/**
* A simple example includes a HTTP post method to add one item to a DynamoDB table.
*/
exports.putItemHandler = async (event) =>
const body, httpMethod, path = event;
if (httpMethod !== 'POST')
throw new Error(`postMethod only accepts POST method, you tried: $httpMethod method.`);
// All log statements are written to CloudWatch by default. For more information, see
// https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-logging.html
console.log('received:', JSON.stringify(event));
// Get id and name from the body of the request
const id, name = JSON.parse(body);
// Creates a new item, or replaces an old item with a new item
// https://docs.aws.amazon.com/AWSjavascriptSDK/latest/AWS/DynamoDB/DocumentClient.html#put-property
const params =
TableName: tableName,
Item: id, name ,
;
await docClient.put(params).promise();
const response =
statusCode: 200,
body,
;
console.log(`response from: $path statusCode: $response.statusCode body: $response.body`);
return response;
;
我运行此程序,但出现“找不到资源”错误。我已确保个人资料详细信息正确无误。
问题在于处理程序中的这一行:const tableName = process.env.SAMPLE_TABLE;
如果我在这里硬编码表名,它可以正常工作。否则该函数总是产生tableName
值“SampleTable”...
它应该采用我提供的环境变量的值。不是“SampleTable”...我做错了什么?
【问题讨论】:
【参考方案1】:local environment filelocal.json
中的键是 lambda 函数名称。
"putItemFunction:"
,在你的情况下不是"putItem:"
。
【讨论】:
以上是关于SAM 调用不会采用本地环境变量的主要内容,如果未能解决你的问题,请参考以下文章