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,41 @@ 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 secrets manager from different products.
54+ """
55+ global api_key
56+ if api_key :
57+ return api_key
58+
59+ import boto3
60+
61+ DD_API_KEY_SECRET_ARN = os .environ .get ("DD_API_KEY_SECRET_ARN" , "" )
62+ DD_API_KEY_SSM_NAME = os .environ .get ("DD_API_KEY_SSM_NAME" , "" )
63+ DD_KMS_API_KEY = os .environ .get ("DD_KMS_API_KEY" , "" )
64+ DD_API_KEY = os .environ .get (
65+ "DD_API_KEY" , os .environ .get ("DATADOG_API_KEY" , "" )
66+ )
67+
68+ if DD_API_KEY_SECRET_ARN :
69+ api_key = boto3 .client ("secretsmanager" ).get_secret_value (
70+ SecretId = DD_API_KEY_SECRET_ARN
71+ )["SecretString" ]
72+ elif DD_API_KEY_SSM_NAME :
73+ api_key = boto3 .client ("ssm" ).get_parameter (
74+ Name = DD_API_KEY_SSM_NAME , WithDecryption = True
75+ )["Parameter" ]["Value" ]
76+ elif DD_KMS_API_KEY :
77+ kms_client = boto3 .client ("kms" )
78+ api_key = decrypt_kms_api_key (kms_client , DD_KMS_API_KEY )
79+ else :
80+ api_key = DD_API_KEY
81+
82+ return api_key
83+
84+
4985def init_api ():
5086 if not os .environ .get ("DD_FLUSH_TO_LOG" , "" ).lower () == "true" :
5187 # Make sure that this package would always be lazy-loaded/outside from the critical path
@@ -54,28 +90,7 @@ def init_api():
5490 from datadog import api
5591
5692 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
93+ api ._api_key = get_api_key ()
7994
8095 logger .debug ("Setting DATADOG_API_KEY of length %d" , len (api ._api_key ))
8196
0 commit comments