In this lesson, we'll explore a real-world scenario in which an EC2 instance is experiencing multiple failed SSH logins, and we want to automatically take the instance offline in response to this potential security event.
Use the Web Server Log Group and the Invalid SSH Login metric filter to trigger a CloudWatch alarm set for 2 data points within 1 minute.
This alarm should publish to an alarm notification SNS topic and send you an email as well as trigger the Lambda function to stop the instance.
Select IAM > Create Role > AWS Service > EC2 > Next: Permissions.
Select the CloudWatchAgentAdminPolicy managed policy.
Select the AmazonEC2RoleforSSM managed policy.
Name the role "CloudWatchAgentAdminRole".
Select Amazon Linux 2.
Create or select a security group with SSH (port 22) open to the public (
Run the CloudWatch Agent Configuration Wizard.
Create a new session using SSM Session Manager.
Note: Do not select CollectD, unless you already installed it using
sudo yum install collectd.
/var/log/secure at the "Do you want to monitor any log files?" prompt.
```sh sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c file:/opt/aws/amazon-cloudwatch-agent/bin/config.json -s ```
The CloudWatch Alarm will notify this topic, and the topic will trigger the Lambda function.
Topic name: AlarmNotificationTopic
Click Secure log group.
Click Create metric filter.
[Mon, day, timestamp, ip, id, status = Invalid*]
Click Test pattern.
Click Assign metric.
Click Create filter.
Click Create alarm.
Invalid login attempts >2 in 1 min for instance\
Note: The description is critical, as the instance ID at the end is used by the Lambda function to stop the instance.
2 for 1 out of 1 datapoints
Make 3 invalid SSH login attempts within 2 minutes.
Verify that the
secure log contains the
Invalid user string.
Verify that the CloudWatch alarm is set.
Verify that the CloudWatch Log for the Lambda function ran.
Verify that the EC2 instance is stopped.