aws-sam-local environment variables

后端 未结 3 1429
暗喜
暗喜 2021-02-05 02:49

I am following the readme here: https://github.com/awslabs/aws-sam-local

I have a lambda written in python 3.6 and its similar to the helloworld example here : https://g

3条回答
  •  北恋
    北恋 (楼主)
    2021-02-05 03:21

    template file

    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
    

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

    then in code

    console.log(process.env.SOME_VAR);
    

    when you run sam local start-api and it will print default value

    when you run sam local start-api --parameter-overrides SomeVar=other_value and it will print other_value

    then if you create file env.json with this content

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

    when you run sam local start-api --env-vars env.json and it will print 123

    p.s. it will work with start-api/start-lambda/invoke all in the same way, but it looks like sam deploy only works with --parameter-overrides SomeVar=other_value and no --env-vars

提交回复
热议问题