Security Monitoring with EventBridge
Build a real-time alert pipeline that emails you when a security group changes.
Introduction
30 Second Summary
Imagine someone quietly opens a back door in your house while you are away. A good security system catches it instantly and sends an alert to your phone.
In this project, you will build the cloud version of that security system on AWS. You will connect CloudTrail, EventBridge, and SNS into a pipeline that detects dangerous network changes and sends you an email alert.
What You'll Build
You will deliberately open a security group to all internet traffic, watch your pipeline catch the change in real time, and see the alert email land in your inbox.
By the end of this project, you'll have:
- A working event-driven alert pipeline that emails you within minutes when someone modifies a security group in your AWS account.
- The ability to read CloudTrail Event History and identify exactly who changed what, when, and from where.
- Firsthand experience diagnosing a real EventBridge rule state gotcha that silently excludes certain CloudTrail events, and knowledge of how to fix it.
- Secret Mission: Add a second detection rule that catches IAM access key creation, building toward multi-threat monitoring.
Are there any prerequisites?
This project assumes you have an AWS account on the free tier and have completed introductory IAM, S3, and VPC projects.
You will also need a Linux machine to follow along.
Before We Start
Before diving into the terminal, let's lock in what you're about to build and why it matters.
Install the AWS CLI and Create a CloudTrail Trail
You cannot monitor what you do not record. Before building any alerts or detection rules, your AWS account needs two things: the AWS CLI on your machine so you can manage AWS from the terminal, and a CloudTrail trail recording every API call to an S3 bucket.
CloudTrail is the audit log for your entire AWS account. Every time someone creates a resource, modifies a security group, or generates an access key, CloudTrail records it. Without this trail running, your alert pipeline later in the project has nothing to detect.
In this step, get ready to:
- Install and configure the AWS CLI v2 on your CachyOS machine.
- Create an S3 bucket and a CloudTrail trail to record every API call in your account.
- Verify the trail is active and logging.
Install AWS CLI v2 on CachyOS
The AWS CLI is a command-line tool that lets you interact with AWS services from your terminal. You will use it for every remaining step in this project.
- Open your terminal.
- Download the official AWS CLI v2 installer by running this command:
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
- Unzip the installer and run it by running these commands:
unzip awscliv2.zip
sudo ./aws/install
What do these commands do?
The curl command downloads the official AWS CLI v2 bundled installer as a zip file. unzip extracts it into an aws directory.
The installer places the CLI in /usr/local/aws-cli and creates a symlink in /usr/local/bin so the aws command is available everywhere.
- Verify the installation by running:
aws --version
✔️ I see aws-cli/2.x.x
The AWS CLI is installed and ready. Move on to the next action.
ⓧ I see aws-cli/1.x.x
You have version 1 installed from your package manager. The v2 installer uses a different path, so v1 may still be the default.
- Run the installer again with the update flag:
sudo ./aws/install --update
- Close and reopen your terminal, then run aws --version again. You should now see aws-cli/2.x.x.
ⓧ Command not found
The installer may not have created the symlink correctly.
- Check that /usr/local/bin is in your PATH by running:
echo $PATH
- If /usr/local/bin is missing, add it to your shell profile and restart your terminal.
- If it is present, try running the full path directly: /usr/local/bin/aws --version.
Now you need to connect the CLI to your AWS account. The aws configure command is an interactive wizard that asks for four values.
- Configure your credentials by running:
aws configure
What will aws configure ask me?
The wizard prompts for four values, one at a time:
- AWS Access Key ID - paste your IAM user's access key ID.
- AWS Secret Access Key - paste your IAM user's secret access key.
- Default region name - enter your preferred region (e.g. us-east-1).
- Default output format - enter json.
- Confirm the CLI is connected to your account by running:
aws sts get-caller-identity
You should see a JSON response showing your Account number, Arn, and UserId. Make a note of your 12-digit account number. You will use it in the next substep.
Seeing an error about credentials?
- Double check that you pasted your Access Key ID and Secret Access Key correctly. Trailing spaces can break authentication.
- Make sure your IAM user has programmatic access enabled. You can check this in the IAM console under your user's security credentials.
- help me debug my AWS CLI credentials
Create the S3 bucket and CloudTrail trail
CloudTrail needs an S3 bucket to store its log files. You will create a bucket, attach a policy that lets CloudTrail write to it, create the trail, and start logging.
- Create your S3 bucket by running this command. Replace your 12-digit account ID with the account number from the previous step:
aws s3 mb s3://cloudtrail-logs-[[AWS_ACCOUNT_ID="your 12-digit account ID"]]
You should see output like make_bucket: cloudtrail-logs-123456789012 confirming the bucket was created.
Why include the account ID in the bucket name?
S3 bucket names must be globally unique across all AWS accounts. Including your account ID makes collisions nearly impossible.
CloudTrail requires a bucket policy that grants it permission to write log files. Without this policy, the trail creation will fail.
- Create a file called bucket-policy.json with the CloudTrail bucket policy by running this command. Replace both instances of your 12-digit account ID and your AWS region with your own values:
cat > bucket-policy.json << 'EOF'
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AWSCloudTrailAclCheck20150319",
"Effect": "Allow",
"Principal": {"Service": "cloudtrail.amazonaws.com"},
"Action": "s3:GetBucketAcl",
"Resource": "arn:aws:s3:::cloudtrail-logs-[[AWS_ACCOUNT_ID="your 12-digit account ID"]]",
"Condition": {
"StringEquals": {
"aws:SourceArn": "arn:aws:cloudtrail:[[AWS_REGION="your AWS region"]]:[[AWS_ACCOUNT_ID="your 12-digit account ID"]]:trail/security-monitor-trail"
}
}
},
{
"Sid": "AWSCloudTrailWrite20150319",
"Effect": "Allow",
"Principal": {"Service": "cloudtrail.amazonaws.com"},
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::cloudtrail-logs-[[AWS_ACCOUNT_ID="your 12-digit account ID"]]/AWSLogs/[[AWS_ACCOUNT_ID="your 12-digit account ID"]]/*",
"Condition": {
"StringEquals": {
"s3:x-amz-acl": "bucket-owner-full-control",
"aws:SourceArn": "arn:aws:cloudtrail:[[AWS_REGION="your AWS region"]]:[[AWS_ACCOUNT_ID="your 12-digit account ID"]]:trail/security-monitor-trail"
}
}
}
]
}
EOF
What does this policy do?
The policy has two statements. The first lets CloudTrail check the bucket's ACL to verify it has permission. The second lets CloudTrail write log files into the bucket under the AWSLogs/ prefix.
The aws:SourceArn condition is a security best practice. It ensures only your specific trail can write to this bucket, preventing unauthorized trails from dumping logs here.
- Attach the policy to your bucket by running:
aws s3api put-bucket-policy --bucket cloudtrail-logs-[[AWS_ACCOUNT_ID="your 12-digit account ID"]] --policy file://bucket-policy.json
This command produces no output on success. Now you can create the trail.
- Create the CloudTrail trail by running:
aws cloudtrail create-trail --name security-monitor-trail --s3-bucket-name cloudtrail-logs-[[AWS_ACCOUNT_ID="your 12-digit account ID"]]
You should see JSON output containing the trail's name, ARN, and S3BucketName confirming the trail was created.
What is a CloudTrail trail?
A trail is a configuration that tells CloudTrail to record API calls and deliver the logs to the S3 bucket you specified. Creating the trail does not start logging. You need to explicitly start it.
- Start logging on the trail by running:
aws cloudtrail start-logging --name security-monitor-trail
This command produces no output on success. Your trail is now actively recording.
Seeing InsufficientS3BucketPolicyException?
- This means the bucket policy does not grant CloudTrail the permissions it needs. Double check that the account ID and region in bucket-policy.json match your actual values exactly.
- Make sure the bucket name in the policy matches the bucket you created. A single character difference will cause a mismatch.
- Re-run the aws s3api put-bucket-policy command after fixing the JSON, then retry aws cloudtrail create-trail.
- help me fix my CloudTrail bucket policy
Verify the trail is active
Before you do anything else, you need to confirm the trail is actually recording. A misconfigured trail silently drops events, which means your alert pipeline later would appear broken when it is really the trail that is at fault.
- Before you run this command, predict: what field in the output would prove the trail is actively recording?
- Check the trail status by running:
aws cloudtrail get-trail-status --name security-monitor-trail
Look for "IsLogging": true in the JSON output. That field confirms CloudTrail is actively recording API calls and delivering logs to your S3 bucket.
IsLogging shows false?
- Run aws cloudtrail start-logging --name security-monitor-trail again. The start-logging command does not return output, so it is easy to miss an error on the first attempt.
- Check for a LatestDeliveryError field in the status output. If present, it usually points to a bucket policy or bucket name mismatch.
- help me get my CloudTrail trail to start logging
Your audit trail is live. Every API call in your AWS account is now being recorded to your S3 bucket. Next up, you will query CloudTrail to see your own recent activity and prove the logs are flowing.
See Your Own Activity in CloudTrail
Your CloudTrail trail is live and recording every API call across your account to S3. That means every action you took in Step 1 is already sitting in the audit log.
Before building automated alerts, you need proof that CloudTrail is actually capturing your activity. In this step, you'll query that log and see your own actions recorded as structured JSON events.
In this step, get ready to:
- Query CloudTrail Event History to find your own recent API calls.
- Examine the JSON fields that your alert pipeline will use to detect threats.
Query your recent CloudTrail events
CloudTrail keeps a 90-day Event History of every management API call in your account, free of charge. This means every bucket you created, every trail you configured, and every permission you changed is searchable right now.
Think about the actions you took in Step 1. You created an S3 bucket and a CloudTrail trail. What events do you think CloudTrail recorded? Before you run the next command, predict what event names you expect to see in the output.
- Query your recent S3 activity by running this command in your terminal:
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventSource,AttributeValue=s3.amazonaws.com --max-results 5
What does this command do?
The aws cloudtrail lookup-events command searches CloudTrail's 90-day Event History for recent API calls.
- --lookup-attributes AttributeKey=EventSource,AttributeValue=s3.amazonaws.com filters results to only show events from the S3 service. This narrows the output to the bucket you created in Step 1.
- --max-results 5 limits the output to five events so the JSON stays readable.
You should see a JSON object containing an Events array. Look for an event with EventName set to CreateBucket and your IAM username in the Username field. That is your own activity, captured automatically.
Not seeing any events?
- Events typically take about 5 minutes to appear in Event History. If you created your bucket recently, wait a few minutes and run the command again.
- Make sure the --lookup-attributes flag is typed exactly as shown. A typo in AttributeKey or AttributeValue will return an error.
- Double check that your AWS CLI is configured for the same region where you created your S3 bucket. Run aws configure get region to confirm.
Still stuck? Help me figure out why my CloudTrail lookup-events command isn't returning results.
Read the anatomy of a CloudTrail event
Each event in the output contains a CloudTrailEvent field. This is a JSON string holding the full event record with every detail about the API call. These are the fields your alert pipeline will consume in the next step.
What do the CloudTrail event fields mean?
- eventName tells you which API action was called. For example, CreateBucket means someone created an S3 bucket.
- userIdentity tells you exactly who made the call. It includes the IAM user or role, the account ID, and the authentication method.
- sourceIPAddress tells you where the call came from. You should see your own IP address for the events you triggered.
- eventTime tells you exactly when the call happened, down to the second.
Together, these four fields answer the core security question: who did what, when, and from where.
This is the raw data your alert pipeline will work with. In the next step, you will build an EventBridge rule that watches for specific eventName values in these events and fires an alert automatically.
You just proved that CloudTrail is silently recording every API call in your account. Next up, you'll turn that raw data into a real-time alert pipeline using SNS and EventBridge.
Build the Alert Pipeline with SNS and EventBridge
In the last step, you proved that CloudTrail is recording every API call in your account. You queried the audit log and saw your own actions captured with fields like eventName and userIdentity.
Manually querying logs works fine for investigating past incidents. Security teams need to know about threats the moment they happen. In this step, you will build the automated pipeline: Amazon SNS for delivering email alerts and Amazon EventBridge for detecting the right events in real time.
In this step, get ready to:
- Create an SNS topic and subscribe your email address.
- Create an EventBridge rule that detects security group changes via CloudTrail.
- Verify the rule is active and correctly configured.
Create an SNS topic and subscribe your email
SNS is a messaging service that pushes notifications to endpoints like email addresses. You will create a topic that serves as the central destination for your security alerts.
- Create an SNS topic named security-alerts by running this command:
aws sns create-topic --name security-alerts
What does this command do?
This creates a new SNS topic and returns its TopicArn (Amazon Resource Name). The ARN uniquely identifies this topic across all of AWS. You will need this ARN in the next commands.
- You should see a JSON response containing a TopicArn field. Copy the full ARN value. It looks something like arn:aws:sns:us-east-1:123456789012:security-alerts.
- Subscribe your email address to the topic by running this command:
aws sns subscribe \
--topic-arn [[SNS_TOPIC_ARN="your SNS topic ARN"]] \
--protocol email \
--notification-endpoint [[YOUR_EMAIL="your email address"]]
What does this command do?
This tells SNS to send email notifications to your address whenever a message is published to the security-alerts topic. The subscription starts in a PendingConfirmation state until you confirm it from your inbox.
- You should see a JSON response with SubscriptionArn showing pending confirmation.
- Check your email inbox for a message from AWS Notifications.
- Click the Confirm subscription link in the email.
- You should see a confirmation page in your browser confirming the subscription is active.
Don't see the confirmation email?
- Check your spam or junk folder. AWS notification emails sometimes end up there.
- Verify the email address you entered in the subscribe command is correct. If it was wrong, run the subscribe command again with the correct address.
- Wait a minute or two. The email can take a short time to arrive.
Still stuck? Why am I not receiving the SNS confirmation email?
Create the EventBridge rule and attach the SNS target
EventBridge watches events flowing through your AWS account and matches them against patterns you define. You will create a rule that catches a specific CloudTrail event: AuthorizeSecurityGroupIngress. This is the API call that opens inbound ports on a security group.
- Create the EventBridge rule by running this command:
aws events put-rule \
--name sg-change-alert \
--event-pattern '{"source":["aws.ec2"],"detail-type":["AWS API Call via CloudTrail"],"detail":{"eventName":["AuthorizeSecurityGroupIngress"]}}' \
--state ENABLED
What does this event pattern do?
The event pattern is a JSON filter that tells EventBridge which events to match. This pattern has three layers:
- source: only events from the EC2 service (aws.ec2).
- detail-type: only events that are CloudTrail API calls (AWS API Call via CloudTrail).
- eventName: only the specific action of authorizing inbound security group rules (AuthorizeSecurityGroupIngress).
All three conditions must match for EventBridge to fire the rule. Only security group ingress changes trigger an alert.
- You should see a JSON response with a RuleArn confirming the rule was created.
- Connect the SNS topic as the rule's target by running this command:
aws events put-targets \
--rule sg-change-alert \
--targets Id=1,Arn=[[SNS_TOPIC_ARN="your SNS topic ARN"]]
What does this command do?
This tells EventBridge where to send events that match the rule. When an AuthorizeSecurityGroupIngress event is detected, EventBridge publishes the full event details to your security-alerts SNS topic. SNS then forwards it to your email.
- You should see a JSON response with "FailedEntryCount": 0 confirming the target was attached successfully.
Seeing a FailedEntryCount greater than 0?
- Double-check that the ARN you pasted matches the one from your aws sns create-topic output exactly.
- Make sure the rule name sg-change-alert matches what you used in the put-rule command.
Still stuck? Why is my EventBridge put-targets command failing?
Verify the rule is active
Before you run the verification command, think about what you expect to see. What state should the rule be in? What should the event pattern contain?
- Check the rule configuration by running this command:
aws events describe-rule --name sg-change-alert
You should see output showing "State": "ENABLED" and an EventPattern field containing AuthorizeSecurityGroupIngress.
What should I see?
The output confirms three things: the rule exists on the default event bus, it is actively listening for events (ENABLED), and the event pattern targets the exact API call you care about.
Rule not showing as ENABLED?
- If you see DISABLED, re-run the put-rule command with --state ENABLED.
- If the command returns an error that the rule does not exist, check the rule name for typos.
Need help? Why is my EventBridge rule not showing as enabled?
Your alert pipeline is wired up and waiting. Next up, you will trigger a real security group change to test whether the alert actually lands in your inbox.
Trigger the Alert and Diagnose the Gotcha
Your alert pipeline is assembled. CloudTrail is logging, EventBridge has a rule, and SNS has a confirmed subscriber. On paper, everything should work.
In this step, you will put the pipeline to the test by deliberately creating a dangerous security group rule. You will also uncover a subtle EventBridge configuration that determines which CloudTrail events your rules can detect.
In this step, get ready to:
- Create a test security group and open port 22 to all internet traffic.
- Discover the EventBridge rule state that controls CloudTrail event matching.
- Receive an email alert proving the full pipeline works end to end.
Create a test security group and open port 22
A security group controls which traffic can reach your AWS resources. Opening port 22 (SSH) to 0.0.0.0/0 is a classic misconfiguration that exposes servers to the entire internet. This is exactly the kind of change your monitoring pipeline should catch.
- Create a test security group in your default VPC by running this command:
aws ec2 create-security-group --group-name test-sg --description "Test security group for alert pipeline"
What does this command do?
- This creates a new security group named test-sg in your default VPC.
- The output includes a GroupId value (like sg-0abc1234def56789) that you need for the next commands.
- Copy the GroupId from the output and save it somewhere handy. You will use it in several upcoming commands.
- Open port 22 to all internet traffic by running this command:
aws ec2 authorize-security-group-ingress --group-id [[SG_ID="your GroupId from the previous output"]] --protocol tcp --port 22 --cidr 0.0.0.0/0
What does this command do?
- authorize-security-group-ingress adds an inbound rule to the security group.
- --protocol tcp --port 22 opens SSH access.
- --cidr 0.0.0.0/0 means any IP address on the internet can connect. This is a dangerous rule that a security team would want to know about immediately.
Before you check your inbox, take a moment to predict. Your EventBridge rule is set to match AuthorizeSecurityGroupIngress events from CloudTrail. Do you think the alert email has already arrived?
- Check your email inbox now. Wait a couple of minutes for the event to propagate.
No alert has arrived yet. CloudTrail events take several minutes to propagate through EventBridge to SNS. But there is also a deeper configuration issue with your rule worth investigating right now.
Already received an alert?
If an alert did arrive, CloudTrail delivered the event faster than usual. Continue with the next substep anyway. You will discover an important configuration gap that affects your rule's coverage of other event types.
Why did I receive an alert even though my rule state is ENABLED?
Diagnose and fix the EventBridge rule state
The EventBridge rule state controls which categories of CloudTrail events your rule can match. Let's inspect the current state of your rule to see if there is a gap.
- Check your rule's current configuration by running this command:
aws events describe-rule --name sg-change-alert
- Look at the State field in the output. It shows ENABLED.
What is the EventBridge rule state gotcha?
The AWS API reference describes the ENABLED state as: the rule is enabled, and EventBridge matches events against the rule, "except for Amazon Web Services management events delivered through CloudTrail." For a security monitoring rule that depends entirely on CloudTrail events, this exclusion signals a gap in coverage.
In practice, ENABLED does match write (mutating) management events like AuthorizeSecurityGroupIngress. But it excludes read-only management events entirely. For comprehensive security monitoring, you want to catch all management events.
The ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS state removes this exclusion. It tells EventBridge to match every management event delivered through CloudTrail, including read-only ones. This is the state you want for any rule that monitors AWS API activity.
- Update your rule to the comprehensive state by running this command:
aws events put-rule \
--name sg-change-alert \
--event-bus-name default \
--state ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS \
--event-pattern '{"source":["aws.ec2"],"detail-type":["AWS API Call via CloudTrail"],"detail":{"eventName":["AuthorizeSecurityGroupIngress"]}}'
What does this command do?
- put-rule updates your existing sg-change-alert rule in place.
- --state ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS tells EventBridge to match all CloudTrail management events with no exclusions.
- The --event-pattern flag re-specifies the same pattern to ensure it is preserved during the update.
- Confirm the update took effect by running this command:
aws events describe-rule --name sg-change-alert
- Verify that the State field now shows ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS.
Still seeing ENABLED?
Double-check that your put-rule command completed without errors. The output should include a RuleArn.
Make sure you included --state ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS with the correct spelling and casing. The value is case-sensitive.
My EventBridge rule state did not update after running put-rule. How do I fix this?
Re-trigger the alert and confirm detection
Your rule now has comprehensive CloudTrail event coverage. Time to generate a fresh event and prove the full pipeline works end to end.
- Revoke the dangerous inbound rule you added earlier by running this command:
aws ec2 revoke-security-group-ingress --group-id [[SG_ID="your GroupId from earlier"]] --protocol tcp --port 22 --cidr 0.0.0.0/0
Why revoke before re-adding?
You need to remove the existing rule first so you can add it again as a fresh action. This generates a new AuthorizeSecurityGroupIngress event in CloudTrail under the updated EventBridge rule state.
- Re-add the dangerous rule to generate a fresh CloudTrail event:
aws ec2 authorize-security-group-ingress --group-id [[SG_ID="your GroupId from earlier"]] --protocol tcp --port 22 --cidr 0.0.0.0/0
Before you check your inbox, predict what will happen. With the rule now set to ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS and a fresh AuthorizeSecurityGroupIngress event generated, do you think the alert will arrive this time?
- Check your email inbox. CloudTrail events can take a few minutes to propagate, so give it up to 5 minutes.
The alert email has arrived. Open it and look at the JSON body inside.
What should I see in the alert email?
- The subject line contains the rule name sg-change-alert.
- The body is a JSON payload from CloudTrail showing the full event details.
- Look for eventName set to AuthorizeSecurityGroupIngress and cidrIp set to 0.0.0.0/0 inside the request parameters.
- The sourceIPAddress field shows your IP address, proving exactly who made the change.
No alert after 5 minutes?
- Confirm your SNS subscription is still active by running aws sns list-subscriptions and checking that your email shows a confirmed status.
- Verify the rule state by running aws events describe-rule --name sg-change-alert and checking for ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS.
- Check your spam or junk folder. SNS notification emails sometimes get filtered.
I am not receiving the EventBridge SNS alert email after waiting 5 minutes. How do I troubleshoot this?
- Now that the alert is confirmed, clean up the dangerous rule by revoking it:
aws ec2 revoke-security-group-ingress --group-id [[SG_ID="your GroupId from earlier"]] --protocol tcp --port 22 --cidr 0.0.0.0/0
Port 22 is now closed again on your test security group. The security group itself stays in place for now.
Secret mission
Add IAM Access Key Detection
Your security pipeline catches one threat. Real monitoring covers many. Can you add a second detection rule that alerts on IAM access key creation, the #1 signal of AWS account compromise?
Clean Up Your Resources
Clean Up Your Resources
Decide whether to keep your resources running, pause them to come back later, or delete them entirely. This project uses only AWS free-tier services, so ongoing costs are effectively $0 for light personal account usage.
Resources you used:
- CloudTrail trail security-monitor-trail logging management events to S3.
- S3 bucket cloudtrail-logs-<account-id> storing CloudTrail log files.
- SNS topic security-alerts with a confirmed email subscription.
- EventBridge rule sg-change-alert on the default event bus.
- EventBridge rule iam-key-creation-alert on the default event bus (Secret Mission).
- VPC security group test-sg created for testing.
Keep everything running
No action needed. Choose this if you are still actively building or want your monitoring pipeline to keep alerting on security group changes and IAM key creation events.
- Your CloudTrail trail continues logging management events. The first trail delivering management events to S3 is free.
- EventBridge rules matching management events are free.
- SNS includes 1,000 email deliveries per month free.
- The AWS CLI remains installed on your machine.
Pause - I'll come back to this later
Shut down active monitoring to reduce noise in your inbox, but keep everything in place so you can re-enable later.
- Disable the EventBridge rules by running:
- Stop CloudTrail logging by running:
aws events disable-rule --name sg-change-alert
aws events disable-rule --name iam-key-creation-alert
aws cloudtrail stop-logging --name security-monitor-trail
To re-enable later, use aws events enable-rule and aws cloudtrail start-logging with the same names.
Delete - I don't want to use this again
Remove all project resources and start fresh. Follow each group of commands in order.
- Delete the EventBridge rules. You must remove targets before deleting each rule. Run these commands to clean up sg-change-alert:
aws events remove-targets --rule sg-change-alert --ids "1"
aws events delete-rule --name sg-change-alert
- Delete the iam-key-creation-alert rule (if you completed the Secret Mission):
aws events remove-targets --rule iam-key-creation-alert --ids "1"
aws events delete-rule --name iam-key-creation-alert
- Delete the SNS topic. This also removes all its subscriptions:
aws sns delete-topic --topic-arn [[SNS_TOPIC_ARN="your security-alerts topic ARN"]]
- Stop and delete the CloudTrail trail:
aws cloudtrail stop-logging --name security-monitor-trail
aws cloudtrail delete-trail --name security-monitor-trail
- Empty and delete the S3 bucket used for CloudTrail logs:
aws s3 rm s3://[[CLOUDTRAIL_BUCKET="your cloudtrail-logs bucket name"]] --recursive
aws s3 rb s3://[[CLOUDTRAIL_BUCKET="your cloudtrail-logs bucket name"]]
- Delete the test security group:
aws ec2 delete-security-group --group-id [[SG_ID="your test security group ID"]]
- Optionally, uninstall the AWS CLI v2. Remove the symlinks and install directory:
sudo rm /usr/local/bin/aws
sudo rm /usr/local/bin/aws_completer
sudo rm -rf /usr/local/aws-cli
What about your AWS credentials?
The commands above do not delete your ~/.aws/ folder, which contains your CLI configuration and credentials. Only delete that folder if you are sure no other tools or SDKs on your machine need it.
Nice Work!
Nice Work!
You just built a real-time security monitoring pipeline on AWS. The moment someone opens a security group to the internet, your pipeline catches the API call through CloudTrail, matches it with an EventBridge rule, and fires an alert to your inbox through SNS. That is the kind of detection pipeline cloud security teams rely on every day.
You've learned how to:
- Build an event-driven alert pipeline using CloudTrail, EventBridge, and SNS that emails you within minutes when a security group is modified in your AWS account.
- Query CloudTrail Event History to read audit logs and identify exactly who changed what, when, and from which IP address.
- Diagnose the EventBridge rule state gotcha and apply the ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS state to ensure comprehensive CloudTrail event matching.
- Secret Mission: Added a second detection rule for IAM access key creation, building a multi-threat monitoring pipeline.
Ready to quiz yourself?