Skip to content

Commit 1f1282b

Browse files
committed
Change variable to map
1 parent a8f1e2b commit 1f1282b

File tree

9 files changed

+68
-54
lines changed

9 files changed

+68
-54
lines changed

.github/workflows/check-deployments.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,10 +62,10 @@ jobs:
6262
cd ..
6363
#
6464
# Compare length and names of files in Zip.
65+
echo "***Comparing deployment package to source code for $DEPLOYMENT"
6566
# Building in Docker doesn't work, some files are still different.
6667
[[ -f $DEPLOYMENT ]] || { echo "Deployment file not found."; exit 1; }
6768
diff \
6869
<(unzip -vqq $DEPLOYMENT | awk '{$2=""; $3=""; $4=""; $5=""; $6=""; print}' | sort -k3 -f) \
6970
<(unzip -vqq ${DEPLOYMENT}_original | awk '{$2=""; $3=""; $4=""; $5=""; $6=""; print}' | sort -k3 -f)
70-
FILES_CHANGED=$?
71-
echo FILES_CHANGED=$FILES_CHANGED
71+
echo "***Comparison completed. Deployment package is up to date."

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,8 @@ Full contributing [guidelines are covered here](.github/contributing.md).
6262
| <a name="input_standalone"></a> [standalone](#input\_standalone) | Deploy ClickOps in a standalone account instead of into an entire AWS Organization. Ideal for teams who want to monitor ClickOps in only their accounts where it is not instrumented at an Organizational level. | `bool` | `false` | no |
6363
| <a name="input_subcription_filter_distribution"></a> [subcription\_filter\_distribution](#input\_subcription\_filter\_distribution) | The method used to distribute log data to the destination. By default log data is grouped by log stream, but the grouping can be set to random for a more even distribution. This property is only applicable when the destination is an Amazon Kinesis stream. Valid values are "Random" and "ByLogStream". | `string` | `"Random"` | no |
6464
| <a name="input_tags"></a> [tags](#input\_tags) | Tags to add to resources in addition to the default\_tags for the provider | `map(string)` | `{}` | no |
65-
| <a name="input_webhooks_for_msteams_notifications"></a> [webhooks\_for\_msteams\_notifications](#input\_webhooks\_for\_msteams\_notifications) | List of webhook URLs for MS Teams notifications. https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook?tabs=dotnet | `list(string)` | `[]` | no |
66-
| <a name="input_webhooks_for_slack_notifications"></a> [webhooks\_for\_slack\_notifications](#input\_webhooks\_for\_slack\_notifications) | List of webhook URLs for Slack notifications. https://api.slack.com/messaging/webhooks | `list(string)` | `[]` | no |
65+
| <a name="input_webhooks_for_msteams_notifications"></a> [webhooks\_for\_msteams\_notifications](#input\_webhooks\_for\_msteams\_notifications) | Map of `custom_name => webhook URL`s for MS Teams notifications. https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook?tabs=dotnet | `map(string)` | `{}` | no |
66+
| <a name="input_webhooks_for_slack_notifications"></a> [webhooks\_for\_slack\_notifications](#input\_webhooks\_for\_slack\_notifications) | Map of `custom_name => webhook URL`s for Slack notifications. https://api.slack.com/messaging/webhooks | `map(string)` | `{}` | no |
6767

6868
----
6969
### Modules

clickopsnotifier/app.py

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,9 @@
3535
ssm = boto3.client("ssm")
3636

3737

38-
def get_webhook(name) -> str:
39-
response = ssm.get_parameter(Name=name, WithDecryption=True)
40-
value = response["Parameter"]["Value"]
41-
return value
38+
def get_webhook_url(parameter_name) -> str:
39+
response = ssm.get_parameter(Name=parameter_name, WithDecryption=True)
40+
return response["Parameter"]["Value"]
4241

4342

4443
_MESSENGERS = None
@@ -51,15 +50,23 @@ def get_messengers() -> List[Messenger]:
5150
_MESSENGERS = []
5251

5352
logging.info("Configuring Slack messengers...")
54-
for webhook_for_slack in WEBHOOKS_FOR_SLACK:
55-
webhook = get_webhook(webhook_for_slack)
56-
messenger = Messenger("slack", webhook)
53+
for parameter_name in WEBHOOKS_FOR_SLACK:
54+
webhook_url = get_webhook_url(parameter_name)
55+
messenger = Messenger(
56+
webhook_type="slack",
57+
webhook_url=webhook_url,
58+
parameter_name=parameter_name,
59+
)
5760
_MESSENGERS.append(messenger)
5861

5962
logging.info("Configuring MSTeams messengers...")
60-
for webhook_for_msteams in WEBHOOKS_FOR_MSTEAMS:
61-
webhook = get_webhook(webhook_for_msteams)
62-
messenger = Messenger("msteams", webhook)
63+
for parameter_name in WEBHOOKS_FOR_MSTEAMS:
64+
webhook_url = get_webhook_url(parameter_name)
65+
messenger = Messenger(
66+
webhook_type="msteams",
67+
webhook_url=webhook_url,
68+
parameter_name=parameter_name,
69+
)
6370
_MESSENGERS.append(messenger)
6471

6572
logging.info(f"There are {len(_MESSENGERS)} messengers configured.")
@@ -238,15 +245,15 @@ def __handle_event(
238245

239246
# Attempt to send messages as well
240247
messengers = get_messengers()
241-
for i, messenger in enumerate(messengers):
248+
for messenger in messengers:
242249
result_messenger = messenger.send(
243250
cloudtrail_event.user_email,
244251
trail_event,
245252
trail_event_origin=trail_event_origin,
246253
standalone=standalone,
247254
)
248255
if not result_messenger:
249-
logging.error(f"Message NOT sent to webhook {i}.")
256+
logging.error(f'Message NOT sent to webhook "{messenger}".')
250257

251258
if not result:
252259
logging.error(f"trail_event={json.dumps(trail_event)}")

clickopsnotifier/messenger.py

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,32 @@
11
import json
22
import requests
33
import logging
4+
import re
5+
6+
WEBHOOK_NAME_REGEXP = r".*webhooks-for-.*?\/(.*)"
47

58

69
class Messenger:
7-
def __init__(self, format: str, webhook: str) -> None:
8-
self.webhook = webhook
9-
self.format = format
10+
def __init__(
11+
self, webhook_type: str, webhook_url: str, parameter_name: str
12+
) -> None:
13+
self.webhook_url = webhook_url
14+
if self.webhook_url is None:
15+
raise ValueError("webhook_url cannot be None")
1016

11-
if format == "slack":
17+
self.webhook_type = webhook_type
18+
if webhook_type == "slack":
1219
self.send = self.__send_slack_message
13-
elif format == "msteams":
20+
elif webhook_type == "msteams":
1421
self.send = self.__send_msteams_message
1522
else:
16-
raise ValueError("Invalid format, must be ['slack', 'msteams']")
23+
raise ValueError("Invalid webhook_type, must be ['slack', 'msteams']")
24+
25+
m = re.match(WEBHOOK_NAME_REGEXP, parameter_name)
26+
self.webhook_name = m.group(1)
27+
28+
def __str__(self) -> str:
29+
return self.webhook_name
1730

1831
def __send_msteams_message(
1932
self, user, trail_event, trail_event_origin: str, standalone: str
@@ -47,10 +60,12 @@ def __send_msteams_message(
4760
}
4861
],
4962
}
50-
response = requests.post(self.webhook, json=payload)
63+
response = requests.post(self.webhook_url, json=payload)
5164
if response.status_code != 200:
52-
logging.info(f"json payload:\n\n{json.dumps(payload)}")
53-
logging.error(f"response.content={response.content}")
65+
logging.info(f"{self.webhook_name} json payload:\n\n{json.dumps(payload)}")
66+
logging.error(
67+
f"{self.webhook_name} response.content:\n\n{response.content}"
68+
)
5469
return False
5570
return True
5671

@@ -122,9 +137,11 @@ def __send_slack_message(
122137
},
123138
]
124139
}
125-
response = requests.post(self.webhook, json=payload)
140+
response = requests.post(self.webhook_url, json=payload)
126141
if response.status_code != 200:
127-
logging.info(f"json payload:\n\n{json.dumps(payload)}")
128-
logging.error(f"response.content={response.content}")
142+
logging.info(f"{self.webhook_name} json payload:\n\n{json.dumps(payload)}")
143+
logging.error(
144+
f"{self.webhook_name} response.content:\n\n{response.content}"
145+
)
129146
return False
130147
return True
152 Bytes
Binary file not shown.
251 Bytes
Binary file not shown.
199 Bytes
Binary file not shown.

main.tf

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -140,23 +140,23 @@ module "clickops_notifier_lambda" {
140140
}
141141

142142
resource "aws_ssm_parameter" "webhooks_for_slack" {
143-
count = length(var.webhooks_for_slack_notifications)
144-
name = "/${var.naming_prefix}/webhooks-for-slack/${count.index}"
145-
description = "Webhook #${count.index} for clickops notifications via Slack."
143+
for_each = var.webhooks_for_slack_notifications
146144

147-
type = "SecureString"
148-
value = var.webhooks_for_slack_notifications[count.index]
145+
name = "/${var.naming_prefix}/webhooks-for-slack/${each.key}"
146+
description = "Webhook \"${each.key}\" for clickops notifications via Slack."
147+
type = "SecureString"
148+
value = each.value
149149

150150
tags = var.tags
151151
}
152152

153153
resource "aws_ssm_parameter" "webhooks_for_msteams" {
154-
count = length(var.webhooks_for_msteams_notifications)
155-
name = "/${var.naming_prefix}/webhooks-for-msteams/${count.index}"
156-
description = "Webhook #${count.index} for clickops notifications via MS Teams."
154+
for_each = var.webhooks_for_msteams_notifications
157155

158-
type = "SecureString"
159-
value = var.webhooks_for_msteams_notifications[count.index]
156+
name = "/${var.naming_prefix}/webhooks-for-msteams/${each.key}"
157+
description = "Webhook \"${each.key}\" for clickops notifications via MS Teams."
158+
type = "SecureString"
159+
value = each.value
160160

161161
tags = var.tags
162162
}

variables.tf

Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -20,27 +20,17 @@ variable "cloudtrail_bucket_name" {
2020
}
2121

2222
variable "webhooks_for_slack_notifications" {
23-
type = list(string)
24-
description = "List of webhook URLs for Slack notifications. https://api.slack.com/messaging/webhooks"
23+
type = map(string)
24+
description = "Map of `custom_name => webhook URL`s for Slack notifications. https://api.slack.com/messaging/webhooks"
2525
sensitive = true
26-
default = []
27-
28-
validation {
29-
condition = length(compact(var.webhooks_for_slack_notifications)) == length(var.webhooks_for_slack_notifications)
30-
error_message = "May not contain empty strings."
31-
}
26+
default = {}
3227
}
3328

3429
variable "webhooks_for_msteams_notifications" {
35-
type = list(string)
36-
description = "List of webhook URLs for MS Teams notifications. https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook?tabs=dotnet"
30+
type = map(string)
31+
description = "Map of `custom_name => webhook URL`s for MS Teams notifications. https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook?tabs=dotnet"
3732
sensitive = true
38-
default = []
39-
40-
validation {
41-
condition = length(compact(var.webhooks_for_msteams_notifications)) == length(var.webhooks_for_msteams_notifications)
42-
error_message = "May not contain empty strings."
43-
}
33+
default = {}
4434
}
4535

4636

0 commit comments

Comments
 (0)