4
4
5
5
logger = logging .getLogger (__name__ )
6
6
KMS_ENCRYPTION_CONTEXT_KEY = "LambdaFunctionName"
7
+ api_key = None
7
8
8
9
9
10
def decrypt_kms_api_key (kms_client , ciphertext ):
@@ -46,6 +47,40 @@ def decrypt_kms_api_key(kms_client, ciphertext):
46
47
return plaintext
47
48
48
49
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
+
49
84
def init_api ():
50
85
if not os .environ .get ("DD_FLUSH_TO_LOG" , "" ).lower () == "true" :
51
86
# Make sure that this package would always be lazy-loaded/outside from the critical path
@@ -54,28 +89,7 @@ def init_api():
54
89
from datadog import api
55
90
56
91
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 ()
79
93
80
94
logger .debug ("Setting DATADOG_API_KEY of length %d" , len (api ._api_key ))
81
95
0 commit comments