assertible / lambda-cloudwatch-slack

Send AWS CloudWatch notifications to a Slack channel using Lambda
https://assertible.com/blog/npm-package-lambda-cloudwatch-slack
MIT License
482 stars 249 forks source link

Add `createHandler` method for programmatic configuration #63

Open Nevon opened 4 years ago

Nevon commented 4 years ago

This PR proposes the addition of a new public method, createHandler. The main use-case for this is to allow the user to inject their own configuration without having to rely on environment variables.

In my particular case, I am storing my secrets in AWS Parameter Store as SecretStrings, as I prefer to not to have to manually do KMS encryption and maintain (and pay for) yet another KMS key, and I don't want to keep my webhook url unencrypted as I'm using this in an open source project where anyone can see the build logs.

Example would be something like this for my case:

const { createHandler, config } = require('lambda-cloudwatch-slack');
const { SSM } = require('aws-sdk')

const parameterStore = new SSM()

let handler
const setupHandler = async () => {
  if (handler != null {
    return handler
  }

  const { Value } = await parameterStore.getParameter({
    Name: process.env.WEBHOOK_URL_PARAMETER,
    WithDecryption: true
  }).promise()

  handler = createHandler({
    ...config,
    unencryptedHookUrl
  })

  return handler
}

exports.handler = async (event, context) => {
  const handler = await setupHandler()
  return handler(event, context)
}

Considered alternatives

I considered writing to process.env['UNENCRYPTED_HOOK_URL'] after looking up the decrypted value, but since config.js is imported immediately, the value will have already been read from the environment before I can look it up.

Note

Since this project doesn't have a test suite, I'm not 100% sure that my code actually works. I haven't had a chance to manually test it yet, as it requires quite a lot of setup. If this PR would be considered to be merged, it will first have to actually be tested.