Search code examples
serverserverless-frameworkaws-serverless

Serverless conditional function deployment by region


Following config is extracted from my serverless.yml

service: test-svc

provider:
  name: aws
  ...

functions:
  apiHandler:
    handler: index.handler
    events:
      - http: ANY /
      - http: 'ANY {proxy+}'
  taskHandler:
    handler: task.handler
    events:
      - sqs:
          ...
  alexaHandler:
    handler: alexa.handler
    events:
     - alexaSmartHome: ...

I want to deploy apiHandler and taskHandler function in only region-a

And deploy alexaHandler in region-b, region-c and region-d.

If I execute the command sls deploy --region us-east-1 all three functions will be deployed, but I don't need that. I need only 2 functions to be deployed.

  1. Using sls deploy function is not an option because it only swaps zip file.
  2. Putting alexaHandler in sub-directory with new serverless.yml didn't work because deployment only packs sub-directory and won't include code from the parent directory. (Many codes are shared between 3 function)

Any suggestion to deal with this requirement?


Solution

  • After going through all the serverless plugin list I found above requirement could be achieved through serverless-plugin-select

    Using this plugin we can select to deploy only a few functions from serverless.yml depending on stage or region value. In my case using region value.

    Following is modified serverless.yml. plugins section added and regions key added in each function.

    service: test-svc
    
    
    plugins:
      - serverless-plugin-select
    
    provider:
      name: aws
      ...
    
    functions:
      apiHandler:
        ...
        regions:
          - us-west-2
      taskHandler:
        ...
        regions:
          - us-west-2
      alexaHandler:
        ...
        regions:
          - eu-west-1
          - us-east-1
          - us-west-2
    

    With the above config, I use the following bash script to deploy for all region.

    #!/usr/bin/env bash
    
    serverless deploy --region eu-west-1
    serverless deploy --region us-east-1
    serverless deploy --region us-west-2