From bba8f71f784bbfd02adbb139331af7580fad6ed2 Mon Sep 17 00:00:00 2001 From: Tian Chu Date: Wed, 13 Nov 2019 20:52:29 -0500 Subject: [PATCH] Support fetching API Key from secrets manager --- README.md | 6 ++++-- datadog_lambda/metric.py | 20 +++++++++++--------- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 85414797..46b4c3df 100644 --- a/README.md +++ b/README.md @@ -56,9 +56,11 @@ functions: ## Environment Variables -The Datadog API must be defined as an environment variable via [AWS CLI](https://docs.aws.amazon.com/lambda/latest/dg/env_variables.html) or [Serverless Framework](https://serverless-stack.com/chapters/serverless-environment-variables.html): +The Datadog API Key must be defined as one of the following environment variables via [AWS CLI](https://docs.aws.amazon.com/lambda/latest/dg/env_variables.html) or [Serverless Framework](https://serverless-stack.com/chapters/serverless-environment-variables.html): -- DD_API_KEY or DD_KMS_API_KEY (if encrypted by KMS) +- DD_API_KEY +- DD_KMS_API_KEY - the KMS-encrypted API Key, requires the `kms:Decrypt` permission +- DD_API_KEY_SECRET_ARN - the Secret ARN to fetch API Key from the Secrets Manager, requires the `secretsmanager:GetSecretValue` permission (also requires `kms:Decrypt` if using a custom CMK) You can also supply or override the API key at runtime: diff --git a/datadog_lambda/metric.py b/datadog_lambda/metric.py index 3a1997e8..6b13eb3b 100644 --- a/datadog_lambda/metric.py +++ b/datadog_lambda/metric.py @@ -107,18 +107,20 @@ def submit_errors_metric(lambda_context): ) -# Decrypt code should run once and variables stored outside of the function -# handler so that these are decrypted once per container +# Set API Key and Host in the module, so they only set once per container +DD_API_KEY_SECRET_ARN = os.environ.get("DD_API_KEY_SECRET_ARN", "") DD_KMS_API_KEY = os.environ.get("DD_KMS_API_KEY", "") -if DD_KMS_API_KEY: - DD_KMS_API_KEY = boto3.client("kms").decrypt( +DD_API_KEY = os.environ.get("DD_API_KEY", os.environ.get("DATADOG_API_KEY", "")) +if DD_API_KEY_SECRET_ARN: + api._api_key = boto3.client("secretsmanager").get_secret_value( + SecretId=DD_API_KEY_SECRET_ARN + )["SecretString"] +elif DD_KMS_API_KEY: + api._api_key = boto3.client("kms").decrypt( CiphertextBlob=base64.b64decode(DD_KMS_API_KEY) )["Plaintext"] - -# Set API Key and Host in the module, so they only set once per container -api._api_key = os.environ.get( - "DATADOG_API_KEY", os.environ.get("DD_API_KEY", DD_KMS_API_KEY) -) +else: + api._api_key = DD_API_KEY logger.debug("Setting DATADOG_API_KEY of length %d", len(api._api_key)) # Set DATADOG_HOST, to send data to a non-default Datadog datacenter