Skip to content

Instantly share code, notes, and snippets.

@mkornatz
Created December 4, 2017 15:21
Show Gist options
  • Save mkornatz/019fbcc8c66c2744b98b2ccf603f359c to your computer and use it in GitHub Desktop.
Save mkornatz/019fbcc8c66c2744b98b2ccf603f359c to your computer and use it in GitHub Desktop.
Retrieves IP of server and sends it to user via Slack. Used when a server boots up.
<?php
$slackWebhookUrl = "https://hooks.slack.com/services/this/comes/from/slack/after/setting/up/a/webhook";
$slackChannel = 'molly';
// Keeps trying to get the IP address for 20 times
$retries = 0;
$ipAddress = null;
while(empty($ipAddress) && $retries < 20) {
$ipAddress = exec("ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1 -d'/'");
if(empty($ipAddress)) {
usleep(100000); //sleep for 100ms
}
$retries++;
}
$dataString = json_encode(array(
"payload" => array(
'channel' => 'molly',
'text' => 'The IP of this server is: ' . $ipAddress,
'username' => 'ipbot'
)
));
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $slackWebhookUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($dataString))
);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment