Search code examples
aws-api-gatewayserverless-frameworkaws-secrets-manager

Serverless: create api key from SecretsManager value


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.


Solution

  • 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}