22import boto3
33import fnmatch
44import json
5+ import lambda_lib
56import logging
67import os
78import requests
1617logger .setLevel (logging .DEBUG )
1718states = {}
1819
19- def get_config ():
20- # Allow different config file to be specified
21- if 'LAMBDA_CONFIG' in os .environ and len (os .getenv ('LAMBDA_CONFIG' )) > 0 :
22- config_file = os .getenv ('LAMBDA_CONFIG' )
23- if config_file .find ("s3://" ) == 0 :
24- # read from S3 or copy default to s3
25- s3_bucket = config_file [5 :len (config_file )].split ("/" )[0 ]
26- sep = "/"
27- s3_object = sep .join (config_file [5 :len (config_file )].split ("/" )[1 :])
28- s3 = boto3 .client ('s3' )
29- try :
30- config_result = s3 .get_object (Bucket = s3_bucket , Key = s3_object )
31- logger .debug ("S3 get config: {}" .format (config_result ))
32- config_raw = config_result ["Body" ].read ()
33- config = json .loads (config_raw )
34- except ClientError as e :
35- logger .warn ("Config not found in S3: {}" .format (e ))
36- logger .warn ("Copying default config to S3" )
37- with open ('config.json' ) as f :
38- config = json .load (f )
39- s3 .put_object (Bucket = s3_bucket , Key = s3_object , Body = json .dumps (config , indent = 2 ))
40- else :
41- logger .debug ("Reading config file: {}" .format (config_file ))
42- with open (config_file ) as f :
43- config = json .load (f )
44- else :
45- logger .debug ("Reading config file: config.json" )
46- with open ('config.json' ) as f :
47- config = json .load (f )
48-
49- logger .debug ("Config before overrides: {}" .format (json .dumps (config , indent = 2 )))
50- # Replace config data with environment data if it exists
51- # Environment variables are keys uppercased
52- for key in config .keys ():
53- if key .upper () in os .environ :
54- value = os .getenv (key .upper ())
55- try :
56- value_json = json .loads (value )
57- logger .debug ("Got json: {}" .format (json .dumps (value_json )))
58- if len (value_json .keys ()) > 0 :
59- config [key ] = value_json
60- except :
61- if len (value ) > 0 :
62- config [key ] = value
63- logger .debug ("Config after overrides: {}" .format (json .dumps (config , indent = 2 )))
64- return config
65-
66- def get_secret (secret_name , endpoint_url , region_name ):
67- session = boto3 .session .Session ()
68- client = session .client (
69- service_name = 'secretsmanager' ,
70- region_name = region_name ,
71- endpoint_url = endpoint_url
72- )
73-
74- try :
75- get_secret_value_response = client .get_secret_value (
76- SecretId = secret_name
77- )
78- except ClientError as e :
79- if e .response ['Error' ]['Code' ] == 'ResourceNotFoundException' :
80- print ("The requested secret " + secret_name + " was not found" )
81- elif e .response ['Error' ]['Code' ] == 'InvalidRequestException' :
82- print ("The request was invalid due to:" , e )
83- elif e .response ['Error' ]['Code' ] == 'InvalidParameterException' :
84- print ("The request had invalid params:" , e )
85- else :
86- # Decrypted secret using the associated KMS CMK
87- # Depending on whether the secret was a string or binary, one of these fields will be populated
88- if 'SecretString' in get_secret_value_response :
89- secret = get_secret_value_response ['SecretString' ]
90- #print(json.dumps(json.loads(secret), indent=2))
91- #print(secret)
92- return secret
93- else :
94- binary_secret_data = get_secret_value_response ['SecretBinary' ]
95- return binary_secret_data
96-
9720def get_slack_channels (s3_bucket , prefix , pattern ):
9821 # Return: list of channel names
9922 channels = []
@@ -296,31 +219,15 @@ def get_slack_hooks(url):
296219 return hooks
297220
298221def write_datadog_slack (config , channels , service_hooks ):
299- # Datadog: url, api_key, app_key
300- # POST: Create integration: Does add, not delete or update. Can have duplicate entries
301- # PUT: Create/Update integration: updates, deletes
302222 data = {}
303223 data ["channels" ] = channels
304224 data ["service_hooks" ] = service_hooks
305225 #print(json.dumps(data, indent=2))
306- url_base = "https://api.datadoghq.com/api/v1/integration/slack"
307- api = "?api_key=" + config ["datadog_api_key" ]
308- app = "&application_key=" + config ["datadog_app_key" ]
309- url = url_base + api + app + "&run_check=true"
310- headers = {"Content-type" : "application/json" }
311- print ("URL: {}" .format (url ))
312- #result = requests.delete(url_base + api + app)
313- #print(result)
314- #result = requests.post(url, data=json.dumps(data), headers=headers)
315- result = requests .put (url , data = json .dumps (data ), headers = headers )
316- print (result )
317- if result .status_code != 204 :
318- logger .error ("Datadog Slack integration update failed with status: {}" .format (result .status_code ))
319- #logger.debug("HTTP response header {}".format(json.dumps(result.headers, indent=2)))
226+ lambda_lib .write_datadog_integration (config , 'slack' , data )
320227
321228def lambda_handler (event , context ):
322229 global states
323- config = get_config ()
230+ config = lambda_lib . get_config ()
324231
325232 # Setup logging
326233 log_level = getattr (logging , config ["log_level" ].upper (), None )
@@ -331,10 +238,12 @@ def lambda_handler(event, context):
331238 logger .debug ("Event: {}" .format (json .dumps (event , indent = 2 )))
332239 logger .debug ("Context: {}" .format (json .dumps (context , indent = 2 )))
333240 channels = get_slack_channels (config ["s3_bucket_parts" ], config ["path_parts" ], config ["parts_pattern" ])
334- slack_webhook = get_secret (config ["secret_name" ], config ["secret_endpoint_url" ], config ["aws_region" ])
241+ # Secrets: DD api, DD app, slack webhook
242+ datadog_keys = json .loads (lambda_lib .get_secret (config ["secrets" ]["datadog_api" ], config ["secret_endpoint_url" ], config ["aws_region" ]))
243+ slack_webhook = lambda_lib .get_secret (config ["secrets" ]["slack_webhook" ], config ["secret_endpoint_url" ], config ["aws_region" ])
335244 slack_hooks = get_slack_hooks (slack_webhook )
336245 #update_slack_channels(channels)
337- write_datadog_slack (config , channels , slack_hooks )
246+ write_datadog_slack (datadog_keys , channels , slack_hooks )
338247
339248 return 'Done'
340249
0 commit comments