[英]Accessing Environment variables in Serverless C#
我正在研究與 C# 一起運行的無服務器項目。 我從這個repo 創建了樣板代碼。 所以我的問題是如何訪問serverless.yml
文件中提到的環境變量以在方法中使用。 我的serverless.yml
文件看起來像這樣。
service: doc-header
provider:
name: aws
runtime: dotnetcore3.1
environment:
MONGODB_URL: ${ssm:/mongoUrl/${self:provider.stage}~true}
package:
individually: true
functions:
docHeaderUpdator:
handler: AwsDotnetCsharp::AwsDotnetCsharp.Handler::TestFunction
package:
artifact: bin/release/netcoreapp3.1/hello.zip
events:
- sqs:
arn:
Fn::GetAtt:
- TestUserQueue
- Arn
batchSize: 10
maximumBatchingWindow: 10
resources:
Resources:
TestUserQueue:
Type: "AWS::SQS::Queue"
Properties:
QueueName: "TestUserQueue-${opt:stage,self:provider.stage}"
FifoQueue: true
VisibilityTimeout: 200
MessageRetentionPeriod: 102800
ReceiveMessageWaitTimeSeconds: 5
我試過使用,
var mongoUrl = Environment.GetEnvironmentVariable("MONGODB_URL");
但似乎不起作用。
正如Martin Costello在評論中解釋的那樣,Lambda 測試工具 3.1 無法識別 serverless.yml 設置的環境變量,即使它無法識別本地設備中設置的本地環境變量。 如果將其部署到 AWS,然后serverless.yml
可以將環境變量應用到 Lambda 運行時,就像普通的 NodeJS 運行時一樣。
如果您還需要在本地環境中使用環境變量進行測試,而無需使用相同的代碼編寫任何其他代碼,
var mongoUrl = Environment.GetEnvironmentVariable("MONGODB_URL");
執行。 所以在我的例子中,我使用 VSCode 作為調試環境,所以我可以通過將此部分添加到您的launch.json
文件來設置環境變量。
"env": {
"MongoDBUrl": "url"
},
完全launch.json
將如下所示。
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "/Users/sandunn/.dotnet/tools/dotnet-lambda-test-tool-3.1",
// More information:
// https://github.com/aws/aws-lambda-dotnet/tree/master/Tools/LambdaTestTool#configure-for-visual-studio-code,
// https://github.com/aws/aws-lambda-dotnet/tree/master/Tools/LambdaTestTool#configure-for-visual-studio-for-mac
"args": [],
"cwd": "${workspaceFolder}",
"console": "internalConsole",
"stopAtEntry": false,
"internalConsoleOptions": "openOnSessionStart",
// Add your Environment variables here.
"env": {
"MongoDBUrl": "url"
}
}
]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.