-
-
Save l0ris/ef52960fde59ef45caf857528e47aaa3 to your computer and use it in GitHub Desktop.
Send AWS EC2 maintenance notification to Slack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'aws-sdk' | |
require 'digest' | |
require 'json' | |
AWS_REGION = "us-east-1" | |
S3_BUCKET = "<YOUR BUCKET>" | |
SLACK_COMPANY = "<YOUR COMPANY>" | |
SLACK_TOKEN = "<YOUR TOKEN>" | |
SLACK_CHANNEL = "#ops" | |
EC2 = Aws::EC2::Client.new(region: AWS_REGION) | |
S3 = Aws::S3::Client.new(region: AWS_REGION) | |
def run_once(deduplication_id) | |
S3.head_object({ | |
bucket: S3_BUCKET, | |
key: deduplication_id, | |
}) | |
rescue Aws::S3::Errors::NotFound | |
S3.put_object({ | |
bucket: S3_BUCKET, | |
key: deduplication_id, | |
body: "1", | |
}) | |
yield | |
end | |
def get_name_for_instance_id(instance_id) | |
EC2.describe_instances({ | |
instance_ids: [instance_id] | |
}).reservations.first.instances.first.tags.select { |x| x.key == "Name" }.first.value | |
rescue | |
"<empty name>" | |
end | |
EC2.describe_instance_status({ | |
filters: [ | |
{ | |
name: "event.code", | |
values: %w{instance-reboot system-reboot system-maintenance instance-retirement instance-stop}, | |
}, | |
] | |
}).instance_statuses.each do |x| | |
id = x.instance_id | |
name = get_name_for_instance_id(id) | |
x.events.each do |event| | |
code = event.code | |
description = event.description | |
not_before = event.not_before || "<empty time>" | |
not_after = event.not_after || "<empty time>" | |
summary = "[`#{code}`] between #{not_before} - #{not_after}" | |
json = { | |
username: "ec2 maintenance check", | |
icon_emoji: ":ghost:", | |
channel: SLACK_CHANNEL, | |
text: "New maintenance event for *#{name}*", | |
fallback: "New maintenance event for #{name}", | |
attachments: [{ | |
color: "#ff4136", | |
fields: [ | |
{ | |
title: "Description", | |
value: description, | |
short: false | |
}, | |
{ | |
title: "Instance ID", | |
value: id, | |
short: true | |
}, | |
{ | |
title: "Code", | |
value: code, | |
short: true | |
}, | |
{ | |
title: "Not Before", | |
value: not_before, | |
short: true | |
}, | |
{ | |
title: "Not After", | |
value: not_after, | |
short: true | |
} | |
], | |
}] | |
} | |
deduplication_id = "#{id}-#{code}" | |
run_once(deduplication_id) do | |
system "curl -s -d 'payload=#{JSON.dump(json)}' 'https://#{SLACK_COMPANY}.slack.com/services/hooks/incoming-webhook?token=#{SLACK_TOKEN}'" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment