aws-sam-local 环境变量

问题描述 投票:0回答:7

我在这里关注自述文件:https://github.com/awslabs/aws-sam-local

我有一个用 python 3.6 编写的 lambda,它与此处的 helloworld 示例类似:https://github.com/awslabs/aws-sam-local/tree/develop/samples/hello-world/python

template.yml 看起来像这样:

AWSTemplateFormatVersion : '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: MyFunction1 API
Resources:
  MyFunction1:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: MyFunction1
      Handler: lambda_module.lambda_handler
      Runtime: python3.6
      CodeUri: lambda.zip
      MemorySize: 128
      Timeout: 10
      Policies:
        -AWSLamdbaBasicExecutionRole
      Events:
        BingLambdaEndpoint:
          Type: Api
          Properties:
            Path: MyFunction1/search
            Method: get

我在 lambda 中有环境变量,但无法在启动时连接它们。文档说我可以创建一个environments.json文件并在invoke命令上附加以下内容:使用invoke的--env-vars参数

我的环境文件与示例类似,但出现错误:

Unable to find environment variable: api_key

environment.json 看起来像这样:

{
  "MyFunction1": {
    "api_key": "123456789",
    "BUCKET_NAME": "testBucket"
  }
}

我运行的命令是这样的:

sam local invoke MyFunction1 --env-vars environment_variables.json -e event.json

任何人都可以提供更多见解吗?

aws-lambda serverless aws-sam-cli
7个回答
87
投票

您想要以这种方式与 SAM Local 一起使用的任何环境变量都需要存在于您的 SAM 模板中。来自此 GitHub 问题

... SAM Local 仅解析 SAM 模板中定义的环境变量。

在模板中,您可以不提供任何值、空字符串,或选择合理的默认值。

模板的一部分,包括环境变量:

Resources:
  MyFunction1:
    Type: 'AWS::Serverless::Function'
    Properties:
      .....
      Environment:
        Variables:
          api_key:
          BUCKET_NAME:

您可以将环境变量文件视为一种机制,用于“覆盖”模板“了解”的环境变量。它不能作为将任意环境变量注入本地运行时的机制。


47
投票

AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Globals: Function: Timeout: 3 Parameters: SomeVar: Type: String Description: My SomeVar Default: default value Resources: HelloWorldFunction: Type: AWS::Serverless::Function Properties: CodeUri: hello-world/ Handler: app.lambdaHandler Runtime: nodejs12.x Environment: Variables: SOME_VAR: !Ref SomeVar Events: HelloWorld: Type: Api Properties: Path: /hello Method: get Outputs: HelloWorldApi: Description: "API Gateway endpoint URL for Prod stage for Hello World function" Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" HelloWorldFunction: Description: "Hello World Lambda Function ARN" Value: !GetAtt HelloWorldFunction.Arn HelloWorldFunctionIamRole: Description: "Implicit IAM Role created for Hello World function" Value: !GetAtt HelloWorldFunctionRole.Arn

来自 
https://github.com/awslabs/aws-sam-cli/issues/1163#issuecomment-557874976

然后在代码中

console.log(process.env.SOME_VAR);

当你运行 
sam local start-api

时,它会打印

default value
当你运行 

sam local start-api --parameter-overrides SomeVar=other_value

时,它会打印

other_value
然后如果您使用此内容创建文件

env.json

{ "PreviewsFunction": { "SOME_VAR": "123" } }

当你运行 
sam local start-api --env-vars env.json

时,它会打印

123
附注它将以相同的方式与 

start-api/start-lambda/invoke

一起使用,但看起来

sam deploy
只能与
--parameter-overrides SomeVar=other_value
一起使用,而不能与
--env-vars
 一起使用
    


12
投票


6
投票

sam local start-api --env-vars env.json

env.json 中的值未被读取。对我来说解决这个问题的是在 env.json 中使用以下格式

"Parameters": { "PARAM_NAME": "VALUE" }

其他格式不适合我:

{ "function": { "PARAM_NAME": "VALUE" } }



2
投票
-n, --env-vars PATH

。这是 JSON 文件,您需要有一个与模板中的资源名称映射的对象。

模板.yaml:

... Resources: HelloWorldFunction: Type: AWS::Serverless::Function Properties: ... Environment: Variables: SOME_VAR: !Ref SomeVar ...

假设变量的文件名是 
.env.local.json

。内容应该像这样匹配:

.env.local.json:

{ "HelloWorldFunction": { "SOME_VAR": "NEW_VALUE" } }

然后你需要运行命令:

sam local start-api --env-vars .env.local.json

    


1
投票
NoEcho

等于

true
,如本示例所示:
Parameters:
  # Build variables
  Stage:
    Type: String
  # Environment variables
  MssqlServer:
    Type: String
    NoEcho: true
  MssqlDatabase:
    Type: String
    NoEcho: true
  MssqlUser:
    Type: String
    NoEcho: true
  MssqlPassword:
    Type: String
    NoEcho: true

然后您可以简单地使用如下命令传递环境变量:

sam deploy --parameter-overrides "MssqlServer='$MSSQL_SERVER' MssqlDatabase='$MSSQL_DATABASE' MssqlUser='$MSSQL_USER' MssqlPassword='$MSSQL_PASSWORD' Stage=dev" --config-env dev



0
投票
不要

不要使用这种方法来获取秘密! 在Cloudformation模板

(默认为

template.yaml)中,定义变量并根据需要引用它们,例如: AWSTemplateFormatVersion: '2010-09-09' Transform: 'AWS::Serverless-2016-10-31' Parameters: TargetEnv: Type: String Description: Target environment name DynamoDB: Type: String Description: ARN of the DynamoDB table SecurityGroups: Type: List<String> Description: List of VPC security groups Subnet: Type: String Description: VPC subnet identifier Globals: Function: Environment: Variables: TargetEnv: !Ref TargetEnv DynamoDB: !Ref DynamoDB … Resources: ServiceRole: Type: 'AWS::IAM::Role' Properties: Policies: - PolicyName: dynamodb PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - dynamodb:Query Resource: !Ref DynamoDB … MyFunction1: Type: AWS::Serverless::Function Properties: Role: !GetAtt ServiceRole.Arn VpcConfig: &vpc_props SecurityGroupIds: !Ref SecurityGroups SubnetIds: - !Ref Subnet …

Globals.Function.Environment.Variables

下列出的变量也可在运行时使用 - 在本例中的 Node.js 中为

process.env.TargetEnv
process.env.DynamoDB
然后,在 SAM 的配置中设置参数值

(默认为

samconfig.yaml,如果您愿意,也可以使用 TOML 格式)。 version: 0.1 default: build: parameters: cached: true parallel: true deploy: parameters: &default_deploy_parameters stack_name: my-service s3_prefix: my-service resolve_s3: true region: eu-central-1 capabilities: CAPABILITY_IAM image_repositories: [] staging: deploy: &staging_deploy parameters: <<: *default_deploy_parameters parameter_overrides: - TargetEnv=staging - HandshakeTable=arn:aws:dynamodb:eu-central-1:07867760868:table/MyTable - SecurityGroups=sg-61f4470b87daef18c,sg-72a87ea4bf7f4b5d2 - Subnet=subnet-16b4ca88aca7ab4b8 local_start_api: *staging_deploy local_invoke: *staging_deploy production: deploy: parameters: <<: *default_deploy_parameters parameter_overrides: - TargetEnv=production - HandshakeTable=arn:aws:dynamodb:eu-central-1:870517811788:table/MyTable - SecurityGroups=sg-9fa4b495c33d84a18,sg-fcb69e4ca84aa7e81 - Subnet=subnet-daad36a5d2a700a8e

最后,您可以通过相应的命令使用模板中定义的环境(
staging

production
)。
sam deploy --config-env staging
sam local start-api --config-env staging
sam local invoke MyFunction1 --config-env staging
sam deploy --config-env production

对于
sam build

,不得指定环境。

    

© www.soinside.com 2019 - 2024. All rights reserved.