Skip to content

Commit af175ef

Browse files
authored
support nested DD_API_KEY secret in lambda forwarder (DataDog#851)
* support nested secret in forwarder * fix secret key name * run black * fix var name * no throw
1 parent 4070f8b commit af175ef

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

aws/logs_monitoring/settings.py

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
# Copyright 2021 Datadog, Inc.
55

66
import base64
7+
import json
78
import logging
89
import os
910

@@ -189,12 +190,40 @@ def __init__(self, name, pattern, placeholder):
189190
connect_timeout=5, read_timeout=5, retries={"max_attempts": 2}
190191
)
191192
# DD API Key
193+
# Check if the DD_API_KEY_SECRET_ARN environment variable is set
192194
if "DD_API_KEY_SECRET_ARN" in os.environ:
193195
SECRET_ARN = os.environ["DD_API_KEY_SECRET_ARN"]
194196
logger.debug(f"Fetching the Datadog API key from SecretsManager: {SECRET_ARN}")
195-
DD_API_KEY = boto3.client("secretsmanager", config=boto3_config).get_secret_value(
196-
SecretId=SECRET_ARN
197-
)["SecretString"]
197+
198+
# Fetch the secret from Secrets Manager
199+
secret_response = boto3.client(
200+
"secretsmanager", config=boto3_config
201+
).get_secret_value(SecretId=SECRET_ARN)
202+
203+
# The secret could be either a plain string or a JSON object
204+
secret_string = secret_response.get("SecretString")
205+
206+
try:
207+
# Try to parse the secret as JSON
208+
secret_json = json.loads(secret_string)
209+
210+
# If it's a JSON object, look for the 'DD_API_KEY' field
211+
if "DD_API_KEY" in secret_json:
212+
DD_API_KEY = secret_json["DD_API_KEY"]
213+
logger.debug(
214+
"Successfully retrieved the Datadog API key from 'DD_API_KEY'."
215+
)
216+
else:
217+
logger.error(
218+
"The secret does not contain the 'DD_API_KEY' field. "
219+
"Please ensure the secret is in the correct format. "
220+
"Not setting the Datadog API key."
221+
)
222+
223+
except json.JSONDecodeError:
224+
# If parsing as JSON fails, treat the secret as a plain string
225+
logger.debug("Secret is not JSON, using it directly as the Datadog API key.")
226+
DD_API_KEY = secret_string
198227
elif "DD_API_KEY_SSM_NAME" in os.environ:
199228
SECRET_NAME = os.environ["DD_API_KEY_SSM_NAME"]
200229
logger.debug(f"Fetching the Datadog API key from SSM: {SECRET_NAME}")

0 commit comments

Comments
 (0)