44
55logger = logging .getLogger (__name__ )
66KMS_ENCRYPTION_CONTEXT_KEY = "LambdaFunctionName"
7+ api_key = None
78
89
910def decrypt_kms_api_key (kms_client , ciphertext ):
@@ -46,6 +47,40 @@ def decrypt_kms_api_key(kms_client, ciphertext):
4647 return plaintext
4748
4849
50+ def get_api_key () -> str :
51+ """
52+ Gets the Datadog API key from the environment variables or secrets manager.
53+ Extracts the result to a global value to avoid repeated calls to the
54+ secrets manager from different products.
55+ """
56+ global api_key
57+ if api_key :
58+ return api_key
59+
60+ import boto3
61+
62+ DD_API_KEY_SECRET_ARN = os .environ .get ("DD_API_KEY_SECRET_ARN" , "" )
63+ DD_API_KEY_SSM_NAME = os .environ .get ("DD_API_KEY_SSM_NAME" , "" )
64+ DD_KMS_API_KEY = os .environ .get ("DD_KMS_API_KEY" , "" )
65+ DD_API_KEY = os .environ .get ("DD_API_KEY" , os .environ .get ("DATADOG_API_KEY" , "" ))
66+
67+ if DD_API_KEY_SECRET_ARN :
68+ api_key = boto3 .client ("secretsmanager" ).get_secret_value (
69+ SecretId = DD_API_KEY_SECRET_ARN
70+ )["SecretString" ]
71+ elif DD_API_KEY_SSM_NAME :
72+ api_key = boto3 .client ("ssm" ).get_parameter (
73+ Name = DD_API_KEY_SSM_NAME , WithDecryption = True
74+ )["Parameter" ]["Value" ]
75+ elif DD_KMS_API_KEY :
76+ kms_client = boto3 .client ("kms" )
77+ api_key = decrypt_kms_api_key (kms_client , DD_KMS_API_KEY )
78+ else :
79+ api_key = DD_API_KEY
80+
81+ return api_key
82+
83+
4984def init_api ():
5085 if not os .environ .get ("DD_FLUSH_TO_LOG" , "" ).lower () == "true" :
5186 # Make sure that this package would always be lazy-loaded/outside from the critical path
@@ -54,28 +89,7 @@ def init_api():
5489 from datadog import api
5590
5691 if not api ._api_key :
57- import boto3
58-
59- DD_API_KEY_SECRET_ARN = os .environ .get ("DD_API_KEY_SECRET_ARN" , "" )
60- DD_API_KEY_SSM_NAME = os .environ .get ("DD_API_KEY_SSM_NAME" , "" )
61- DD_KMS_API_KEY = os .environ .get ("DD_KMS_API_KEY" , "" )
62- DD_API_KEY = os .environ .get (
63- "DD_API_KEY" , os .environ .get ("DATADOG_API_KEY" , "" )
64- )
65-
66- if DD_API_KEY_SECRET_ARN :
67- api ._api_key = boto3 .client ("secretsmanager" ).get_secret_value (
68- SecretId = DD_API_KEY_SECRET_ARN
69- )["SecretString" ]
70- elif DD_API_KEY_SSM_NAME :
71- api ._api_key = boto3 .client ("ssm" ).get_parameter (
72- Name = DD_API_KEY_SSM_NAME , WithDecryption = True
73- )["Parameter" ]["Value" ]
74- elif DD_KMS_API_KEY :
75- kms_client = boto3 .client ("kms" )
76- api ._api_key = decrypt_kms_api_key (kms_client , DD_KMS_API_KEY )
77- else :
78- api ._api_key = DD_API_KEY
92+ api ._api_key = get_api_key ()
7993
8094 logger .debug ("Setting DATADOG_API_KEY of length %d" , len (api ._api_key ))
8195
0 commit comments