Running runbooks 2 – Security and DevSecOps with Python

We can now create a separate alarm for our test 1 instance and it will be shown graphically to give you an idea of what is happening with the metric currently:

Figure 6.6 – Creating an alarm metric

5. Next, let’s set the condition for the trigger for the alarm to be under 20,000 bytes of network input over a period of five minutes:

Figure 6.7 – Setting a threshold for the alarm

6. Name the alarm test1-alarm in the field asking you for the alarm name and we’re good to go.

Now, we can look at the alarm on the Details tab and find the EventBridge rules, which we will need to set up the EventBridge trigger:

Figure 6.8 – Alarm configuration details

7. Then, go to Amazon EventBridge in the AWS section, and then to the Rules tab, where you will create a new event. On the first page, select Rule with an Event pattern and then move on to the next page. Here, you will paste the EventBridge rule that you acquired from the alarm:

Figure 6.9 – Pattern creation for event bridge

8. Now that you have the pattern, press Next, then in another tab, open AWS Lambda. Here, we will write our Python code to execute the restart of the EC2 instance.

In AWS Lambda, choose the Python execution time and maintain all of the default settings otherwise. Then, add the following code:

import json
import boto3
client = boto3.client(‘ssm’)
def lambda_handler(event, context):
    instance_id = event[“instanceids”]
    client.send_command(InstanceIds = [instance_id], DocumentName = “AWS-RestartEC2Instance”)
    return “Command to restart has been sent.”

This code will send the command of the playbook document to restart the EC2 instance.

Now, let’s select Lambda function as the target for the EventBridge:

Figure 6.10 – Target Lambda function

9. Keep hitting Next until you create the EventBridge rule. When the alarm is triggered, that rule will trigger and run the Lambda function. This will restart the instance and keep doing so until the network input has been restored to acceptable levels.

Now, in this example, we saw an application that is based on an immediate reaction and implementation. This is good if your system is under some sort of attack meant to overwhelm it or to exploit something that you can’t patch. However, attacks don’t usually come in ones. They are targeted and frequent, constantly trying to find some sort of vulnerability from which to attack your workload. To help understand potential attack patterns and learn more about how your workload handles changes in general, you can use pattern analysis of monitored logs.

Leave a Reply

Your email address will not be published. Required fields are marked *