如何在“ sam package / deploy”运行时指定AutoPublishAlias?

时间:2020-03-09 20:38:53

标签: aws-lambda aws-serverless

我将我们的AWS SAM部署包装在Jenkins中,作为CI / CD管道的一部分。例如,当我们合并时,我只想向lambda添加“活动”别名,但是我希望“分支构建”不包含别名。这使开发人员无需“实时”地在AWS中测试代码。除了在我运行“ sam package / deploy”之前用sed替换template.yaml的一部分之外,还有其他方法可以做到这一点吗?

-更新- 看起来我可以使用Parameters在lambda中创建环境,但是我不知道如何在它们之间切换。看起来像:

Parameters:
  MyEnv:
    Description: Environment of this stack of resources
    Type: String
    Default: testing
    AllowedValues: 
      - testing
      - prod

然后我可以引用此w /:

    Environment:
      Variables:
        ENV: !Ref: MyEnv

如果有人知道如何在运行时切换此参数来解决我的问题。

1 个答案:

答案 0 :(得分:1)

我已经开始工作了。我的template.yaml:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  sams-app
Globals:
  Function:
    Timeout: 3
Parameters:
  Stage:
    Type: String
    Description: Which stage the code is in
    Default: test
    AllowedValues:
      - test
      - prod
Resources:
  HelloWorldSQSFunction:
    Type: AWS::Serverless::Function 
    Properties:
      Role: arn:aws:iam::xxxxxxxxxxxx:role/service_lambda_default1
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.7
      AutoPublishAlias: !Ref Stage
      DeploymentPreference:
       Type: AllAtOnce
      Environment:
        Variables:
          STAGE: !Ref Stage
Outputs:
  HelloWorldSQSFunction:
    Description: "Hello World SQS Lambda Function ARN"
    Value: !GetAtt HelloWorldSQSFunction.Arn

我的lambda代码:

import json
import os

def lambda_handler(event, context):
    stage = os.environ['STAGE']
    print(f"My stage is: {stage}")

    return {
        "statusCode": 200,
    }

并在本地运行(我正在使用Cloud9):

DEVELOPER:~/environment/sams-app $ sam local invoke --parameter-overrides Stage=prod
Invoking app.lambda_handler (python3.7)

Fetching lambci/lambda:python3.7 Docker container image......
Mounting /home/ec2-user/environment/sams-app/hello_world as /var/task:ro,delegated inside runtime container
START RequestId: 85da81b1-ef74-1b7d-6ad0-a356f4aa8b76 Version: $LATEST
My stage is: prod
END RequestId: 85da81b1-ef74-1b7d-6ad0-a356f4aa8b76
REPORT RequestId: 85da81b1-ef74-1b7d-6ad0-a356f4aa8b76  Init Duration: 127.56 ms        Duration: 3.69 ms       Billed Duration: 100 ms Memory Size: 128 MB     Max Memory Used: 22 MB

{"statusCode":200}

要注意的一件事是,这将导致您的“ sam validate”失败。有关此信息,请参见:https://github.com/awslabs/serverless-application-model/issues/778

特别感谢JLarky对本主题的评论:aws-sam-local environment variables