问题
I need help with one AWS Step. I know we can send an SNS Notification when the Instance is Stopped, terminated, starting and pending stages. But how do we send a notification when the EC2 instance is rebooted?
Thanks!
回答1:
If a reboot is issued within the instance, then this will not be detected by AWS. It is just the operating system doing its own things.
If a reboot is issued through the AWS management console or an API call, the instance does not actually change state. From Instance Lifecycle - Amazon Elastic Compute Cloud:
Rebooting an instance is equivalent to rebooting an operating system. The instance remains on the same host computer and maintains its public DNS name, private IP address, and any data on its instance store volumes. It typically takes a few minutes for the reboot to complete, but the time it takes to reboot depends on the instance configuration.
Therefore, the only way to react to the reboot command being issued via the AWS console or API is to create an AWS CloudWatch Events rule that receives all Amazon EC2 events and then checks whether it is specifically for a RebootInstances
command.
The rule would look like:
{
"source": [
"aws.ec2"
],
"detail-type": [
"AWS API Call via CloudTrail"
],
"detail": {
"eventSource": [
"ec2.amazonaws.com"
],
"eventName": [
"RebootInstances"
]
}
}
It can then trigger an Amazon SNS notification, which will include the instanceId
.
However, the notification is not very pretty — it consists of a blob of JSON. If you want to send a nicer-looking message, see: amazon web services - Email notification through SNS and Lambda - Stack Overflow
回答2:
Instead of monitoring Cloudtrail you could create a cron entry on instance that will execute @reboot (example here) and send sns notification using aws cli sns publish.
回答3:
You can use the crontab with @reboot against a script to run.
$ crontab -e
@reboot $(python /home/ec2-user/sms.py)
for the python script sms.py
at /home/ec2-user
sms.py (change the AWS region if required):
import boto3
import json
client = boto3.client('sns', region_name='us-west-2')
msg = 'Instance reboot!'
response = client.publish(
PhoneNumber='+1XXXXXXXXXX',
Message=msg)
print(response)
Make sure boto3 is installed on the instance - $ pip install boto3 --user
来源:https://stackoverflow.com/questions/58942559/send-sns-notification-when-ec2-instance-is-rebooted