[英]How to pass an environment variable to an AWS Lambda function using the Serverless framework?
I am using the aws-node template. 我正在使用aws-node模板。 I want to do something like this:
我想做这样的事情:
sls deploy URL='https://postman-echo.com/post'
Where URL is the environment variable. 其中URL是环境变量。 I am trying to pass this env variable to my serverless.yml
我试图将此env变量传递给我的serverless.yml
provider:
name: aws
runtime: nodejs8.10
stage: dev
region: us-west-2
environment:
URL: ${env:URL}
Then access it in my handler.js 然后在我的handler.js中访问它
const axios = require('axios');
module.exports.hello = async (event, context) => {
console.log("Lambda invoked\n")
await axios.post(
process.env.URL // Accessing the environment variable.
).then(function (response) {
console.log(`Status: ${response.status}`)
})
.catch(function (error) {
console.log(`Error`)
console.error(error);
});
return {
statusCode: 200,
body: JSON.stringify({
message: 'Function executed successfully!',
input: event
}),
};
};
I susspect that the issue is in how I am passing the environment variable to the program but my research has been to no avail. 我认为问题在于我如何将环境变量传递给程序,但我的研究无济于事。
Don't pass the variable along with the deploy command. 不要将变量与deploy命令一起传递。 Instead set it from the terminal first:
而是首先从终端设置它:
In your terminal, run: 在您的终端中,运行:
URL='https://postman-echo.com/post'
and then run 然后跑
sls deploy
Alternatively, you can use a plugin: 或者,您可以使用插件:
Here's a plguin to that: https://github.com/colynb/serverless-dotenv-plugin 这是一个问题: https : //github.com/colynb/serverless-dotenv-plugin
npm i -D serverless-dotenv-plugin
then add the plugin to your config file: 然后将插件添加到配置文件中:
service: myService
plugins:
- serverless-dotenv-plugin
...
create your usual dotenv file .env
and then access as usual: 创建您通常的dotenv文件
.env
然后像往常一样访问:
...
provider:
name: aws
runtime: nodejs6.10
stage: ${env:STAGE}
region: ${env:AWS_REGION}
...
And if you really need to run it from the console with different urls flags, (though I'd recommend using just one .env file without the command flags) do this: 如果你真的需要从控制台运行它与不同的urls标志,(虽然我建议只使用一个没有命令标志的.env文件)执行此操作:
Put your different urls in: .env.url1
.env.url2
.env.url3
将您的不同网址放在:
.env.url1
.env.url2
.env.url3
and then: 然后:
sls deploy --env url1
The code that you posted works. 您发布的代码有效。 You just have to pass URL as an environment variable and NOT as an argument.
您只需将URL作为环境变量传递而不是作为参数传递。
This should work (passing URL as an environment variable): 这应该工作(将URL作为环境变量传递):
$ URL='https://postman-echo.com/post' sls deploy
This won't work (you're passing URL as an argument to sls deploy
): 这不起作用(您将URL作为参数传递给
sls deploy
):
$ sls deploy URL='https://postman-echo.com/post'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.