Skip to content

Instantly share code, notes, and snippets.

@janyksteenbeek
Last active October 8, 2021 13:07
Show Gist options
  • Save janyksteenbeek/fd2944adc04ea6fcfb7dd54c384773e7 to your computer and use it in GitHub Desktop.
Save janyksteenbeek/fd2944adc04ea6fcfb7dd54c384773e7 to your computer and use it in GitHub Desktop.
Report Cisco DNA web hook alerts to Slack
<?php
// Setting up Slack Webhook URI
$slackUrl = 'https://hooks.slack.com/services/HIER_JE_WEBHOOK_URL';
$ciscoDnaUrl = 'https://DNA_IP/'; // Always add trailing slash
$ciscoRequest = json_decode(file_get_contents('php://input'));
// Checking wheter or not is a valid Cisco DNS webhook
if(empty($ciscoRequest) || empty($ciscoRequest->ciscoDnaEventLink)) {
echo "Invalid Cisco DNA event. Aborting.";
http_response_code(400);
exit();
}
// Constructing a Slack message
$message = <<<EOL
{
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": "Cisco DNA alert: [eventid]",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": "A new event was reported / an update was reported",
"emoji": true
}
},
{
"type": "section",
"fields": [eventdata]
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Learn more about [eventid]"
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "View event in Cisco DNA",
"emoji": true
},
"value": "dna",
"url": "[eventurl]",
"action_id": "button-action"
}
}
]
}
EOL;
// Compiling sections of data
$fields = [];
foreach($ciscoRequest->data as $key => $value) {
$fields[] = [
'type' => 'mrkdwn',
'text' => "*".$key."*\n" . $value
];
}
// Pretty printing event data
$eventData = json_encode($fields);
// Replacing with actual data
$message = str_replace('[eventid]', $ciscoRequest->eventId, $message);
$url = str_replace('https://&lt;DNAC_IP_ADDRESS&gt;/', $ciscoDnaUrl, $ciscoRequest->ciscoDnaEventLink);
$message = str_replace('[eventurl]', $url, $message);
$message = str_replace('[eventdata]', $eventData, $message);
$message = json_encode(json_decode($message));
// Sending message to Slack
$data = "payload=" .$message;
$ch = curl_init($slackUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment