How to specify AutoPublishAlias at runtime of 'sam package/deploy'?

Viewed 526

I am wrapping our AWS SAM deployment in Jenkins as part of our CI/CD pipeline. I only want to add the "live" alias to the lambdas when we are merging for example, yet I want "branch builds" to be without an alias. This allows developers to test the code in AWS without it being "live". Other than sed replacing part of the template.yaml before I run "sam package/deploy" is there some other way to accomplish this?

--UPDATE-- It looks like I can use Parameters to create environments in my lambda, but I don't know how to toggle between them. This would look like:

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

Then I can reference this w/:

    Environment:
      Variables:
        ENV: !Ref: MyEnv

If someone knows how to toggle this parameter at runtime that solves my problem.

1 Answers

I got this working. My 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

My lambda code:

import json
import os

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

    return {
        "statusCode": 200,
    }

And to run it locally (I'm using 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}

One thing to note is that this will cause your "sam validate" to fail. For info on that, see: https://github.com/awslabs/serverless-application-model/issues/778

Special thanks to JLarky for the comment on this thread: aws-sam-local environment variables

Related