5

I have a Serverless stack deploying an API to AWS. I want to protect it using an API key stored in Secrets manager. The idea is to have the value of the key in SSM, pull it on deploy and use it as my API key.

serverless.yml

service: my-app
frameworkVersion: '2'

provider:
  name: aws
  runtime: nodejs12.x
  ...
  apiKeys:
    - name: apikey
      value: ${ssm:myapp-api-key}

As far as I can tell, the deployed API Gateway key should be the same as the SSM Secret, yet when I look in the console, the 2 values are different. What am I overlooking? No error messages either.

xShirase
  • 11,975
  • 4
  • 53
  • 85

2 Answers2

5

I ran into the same problem a while ago and I resorted to using the serverless-add-api-key plugin as it was not comprehensible for me when Serverless was creating or reusing new API keys for API Gateway.

With this plugin your serverless.yml would look something like this:

service: my-app
frameworkVersion: '2'

plugins:
  - serverless-add-api-key

custom:
  apiKeys:
    - name: apikey
      value: ${ssm:myapp-api-key}

functions:
  your-function:
    runtime: ...
    handler: ...
    name: ...
    events:
      - http:
          ...
          private: true

You can also use a stage-specific configuration:

custom:
  apiKeys:
    dev:
      - name: apikey
        value: ${ssm:myapp-api-key}
yvesonline
  • 4,609
  • 2
  • 21
  • 32
  • That's what I ended up doing, worked perfectly. thanks for the answer! Worth mentioning that it didn't seem to work when the `plugins` section wasn't at the top of the yml file (above `provider` probably suffices) – xShirase May 12 '21 at 15:51
0

This worked well for me:

custom:
  apiKeys:
    - name: apikey
      value: ${ssm:/aws/reference/secretsmanager/dev/user-api/api-key}
      deleteAtRemoval: false # Retain key after stack removal
functions:
  getUserById:
    handler: src/handlers/user/by-id.handler
    events:
      - http:
          path: user/{id}
          method: get
          cors: true
          private: true
ChrisRich
  • 8,300
  • 11
  • 48
  • 67