AWS Builder Center

Autonomous Cloud Security Watchdog Agent

A serverless, self-running agent built in Free Tier that wakes up on a schedule, checks for threat intelligence, and posts real-time, rich alerts to Discord.

Series: Lambda Series (1 article)

  1. 1
    Autonomous Cloud Security Watchdog Agent This article

Building an Autonomous Cloud Security Watchdog Agent on AWS Free Tier

A serverless, self-running background agent built completely within the AWS Free Tier. It wakes up on a schedule (or reacts to AWS account events), checks for threat intelligence, maintains state memory, and posts real-time, rich alert cards directly to a Discord channel.
Discord Demo Link:  demo 

🛠️ Functionality & Core Benefits

Key Features

  • Scheduled & Event-Driven Execution: Wakes up on a cron schedule via Amazon EventBridge or triggers instantly when an AWS account activity occurs (e.g., IAM key creation).
  • Stateful Deduplication: Queries Amazon DynamoDB memory so you are notified only about new threats, eliminating alert fatigue.
  • Rich Messaging Interface: Delivers formatted, color-coded threat embeds (Critical/High/Moderate) directly to Discord.
  • Routine Heartbeat Checks: Sends a daily "All Systems Clear" message when no new vulnerabilities are found so you know the system is running smoothly.

Key Benefits

  • 100% Free Tier Compliant: Uses AWS Lambda, DynamoDB, and EventBridge well within their permanent free allowances.
  • Zero Infrastructure to Manage: Fully serverless architecture running on Python 3.12 without external library dependencies.
  • Immediate Context: High-risk vulnerabilities and account events are delivered straight to your team chat before you open your workstation.

🧰 Prerequisites

Before deploying the project, ensure you have:
  1. An AWS Account with access to Lambda, DynamoDB, IAM, and EventBridge.
  1. A Discord Server where you have admin permissions to create webhooks.
  1. Basic familiarity with the AWS Console and Python.

🏗️ Step-by-Step Deployment Guide

Step 1: Set Up a Discord Webhook

  1. Open Discord and open the target channel settings (e.g.,  #security-alerts ).
  1. Go to Integrations → Webhooks → Click New Webhook.
  1. Name it  Cloud Security Watchdog  and click Copy Webhook URL.


Step 2: Create the Amazon DynamoDB Memory Table

  1. Navigate to the DynamoDB Console → Click Create table.
  1. Configure the settings:
  • Table name:  WatchdogMemory 
  • Partition key:  advisory_id  (String)
  1. Set Table Class/Capacity to On-Demand (or default provisioned) and click Create table.


Step 3: Configure the IAM Execution Role

  1. Open the IAM Console → Roles → Create role.
  1. Select AWS Service → Lambda.
  1. Attach the managed policy  AWSLambdaBasicExecutionRole .
  1. Create an Inline Policy granting access to DynamoDB:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:GetItem",
"dynamodb:PutItem"
],
"Resource": "*"
}
]
}

  1. Name the role  SecurityWatchdogRole  and save it.
Step 4: Deploy the AWS Lambda Agent
  1. Open AWS Lambda → Create function:
  • Name:  SecurityWatchdogAgent 
  • Runtime:  Python 3.12 
  • Role: Choose  SecurityWatchdogRole .
  1. Under Configuration → Environment variables, add:
  •  DISCORD_WEBHOOK_URL : (Your Webhook URL)
  •  TABLE_NAME :  WatchdogMemory 
  1. Under General Configuration, update the Timeout to  30 seconds .
  1. Paste the following production code into  lambda_function.py  and click Deploy:
import os
import json
import urllib.request
import boto3
from datetime import datetime

# AWS Services
dynamodb = boto3.resource('dynamodb')

# Environment Variables
TABLE_NAME = os.environ.get('TABLE_NAME', 'WatchdogMemory')
DISCORD_WEBHOOK_URL = os.environ.get('DISCORD_WEBHOOK_URL')

def fetch_latest_advisories():
"""Fetches high & critical advisories from GitHub's public Security Advisory API."""
url = "https://api.github.com/advisories?severity=high&per_page=5"
req = urllib.request.Request(url, headers={'User-Agent': 'AWS-Lambda-Agent'})
try:
with urllib.request.urlopen(req) as response:
if response.status == 200:
return json.loads(response.read().decode())
except Exception as e:
print(f"Error fetching security advisories: {e}")
return []

def filter_unseen(advisories):
"""Checks DynamoDB state memory to prevent duplicate alerts."""
table = dynamodb.Table(TABLE_NAME)
new_items = []
for adv in advisories:
adv_id = adv.get('ghsa_id')
response = table.get_item(Key={'advisory_id': adv_id})
if 'Item' not in response:
new_items.append(adv)
table.put_item(Item={
'advisory_id': adv_id,
'processed_at': datetime.utcnow().isoformat(),
'summary': adv.get('summary', '')
})
return new_items

def build_github_embeds(advisories):
"""Formats GitHub advisories into native Discord Rich Embed cards."""
embeds = []
color_map = {
'critical': 15158332, # Red
'high': 15105570, # Orange
'moderate': 16776960 # Yellow
}

for adv in advisories[:5]:
severity = adv.get('severity', 'high').lower()
# Safely extract ecosystem
vulnerabilities = adv.get('vulnerabilities') or []
ecosystem = 'N/A'
if vulnerabilities and len(vulnerabilities) > 0:
pkg = vulnerabilities[0].get('package') or {}
ecosystem = pkg.get('ecosystem', 'N/A')

embed = {
"title": f"🛡️ {adv.get('summary')}",
"url": adv.get('html_url'),
"color": color_map.get(severity, 3447003),
"fields": [
{
"name": "Severity",
"value": f"`{severity.upper()}`",
"inline": True
},
{
"name": "GHSA ID",
"value": f"`{adv.get('ghsa_id')}`",
"inline": True
},
{
"name": "Ecosystem",
"value": f"`{ecosystem}`",
"inline": True
},
{
"name": "Description",
"value": (adv.get('description') or 'No details provided.')[:280] + "..."
}
],
"footer": {"text": "AWS Autonomous Security Watchdog Agent"},
"timestamp": datetime.utcnow().isoformat()
}
embeds.append(embed)
return embeds

def build_aws_event_embed(event_data):
"""Formats incoming AWS CloudTrail / IAM events into a Discord alert card."""
detail = event_data.get('detail', {})
event_name = detail.get('eventName', 'Unknown AWS Event')
event_source = detail.get('eventSource', 'aws.iam')
user_identity = detail.get('userIdentity', {}).get('userName', 'Unknown User')
region = event_data.get('region', 'us-east-1')

embed = {
"title": f"🚨 AWS Account Activity: `{event_name}`",
"description": f"An AWS security-relevant API action was detected in account context.",
"color": 15158332, # Red
"fields": [
{
"name": "Event Name",
"value": f"`{event_name}`",
"inline": True
},
{
"name": "IAM User / Identity",
"value": f"`{user_identity}`",
"inline": True
},
{
"name": "AWS Region",
"value": f"`{region}`",
"inline": True
},
{
"name": "Source Service",
"value": f"`{event_source}`",
"inline": False
}
],
"footer": {"text": "AWS Real-Time Security Event Watchdog"},
"timestamp": datetime.utcnow().isoformat()
}
return [embed]

def send_heartbeat_notification():
"""Posts a green 'All Systems Clear' heartbeat card."""
payload = {
"username": "Cloud Security Watchdog",
"avatar_url": "https://cdn-icons-png.flaticon.com/512/2092/2092663.png",
"embeds": [
{
"title": "✅ Watchdog Routine Check: All Clear",
"description": "The autonomous agent woke up, checked advisory feeds, and found **0 new critical vulnerabilities**.",
"color": 3066993, # Green
"fields": [
{
"name": "Status",
"value": "`HEALTHY / NO ACTION REQUIRED`",
"inline": True
},
{
"name": "Memory Sync",
"value": "`DynamoDB State Synced`",
"inline": True
}
],
"footer": {"text": "AWS Autonomous Security Watchdog Agent"},
"timestamp": datetime.utcnow().isoformat()
}
]
}
_post_to_discord(payload)

def send_alert_notification(embeds, message_text="⚠️ **New Autonomous Security Briefing Available:**"):
"""Posts alert embeds to Discord."""
payload = {
"username": "Cloud Security Watchdog",
"avatar_url": "https://cdn-icons-png.flaticon.com/512/2092/2092663.png",
"content": message_text,
"embeds": embeds
}
_post_to_discord(payload)

def _post_to_discord(payload):
if not DISCORD_WEBHOOK_URL:
print("Error: DISCORD_WEBHOOK_URL environment variable is missing!")
return

headers = {'Content-Type': 'application/json', 'User-Agent': 'AWS-Lambda-Agent'}
data = json.dumps(payload).encode('utf-8')
req = urllib.request.Request(DISCORD_WEBHOOK_URL, data=data, headers=headers, method='POST')
try:
with urllib.request.urlopen(req) as response:
print(f"Discord response status code: {response.status}")
except Exception as e:
print(f"Failed to post notification to Discord: {e}")

def lambda_handler(event, context):
print("Agent waking up...")
# 1. Check if invoked by an AWS EventBridge CloudTrail event (e.g., CreateAccessKey)
if isinstance(event, dict) and event.get('detail-type') == 'AWS API Call via CloudTrail':
print("Detected direct AWS event trigger!")
embeds = build_aws_event_embed(event)
send_alert_notification(embeds, message_text="🚨 **AWS Infrastructure Security Alert:**")
return {"status": "AWS_EVENT_PROCESSED"}

# 2. Default Scheduled Routine Scan (GitHub Advisories)
raw_advisories = fetch_latest_advisories()
new_advisories = filter_unseen(raw_advisories)
if not new_advisories:
print("No new advisories found. Sending daily heartbeat ping...")
send_heartbeat_notification()
return {"status": "HEARTBEAT_SENT"}
embeds = build_github_embeds(new_advisories)
send_alert_notification(embeds)
print("Agent finished task successfully!")
return {"status": "ALERTS_SENT", "count": len(new_advisories)}

Step 5: Schedule Automated Execution via EventBridge

  1. Open Amazon EventBridge → Schedules → Create schedule.
  1. Schedule Pattern: Recurring Schedule → Cron-based ( cron(0 7 * * ? *)  for 7:00 AM UTC daily).
  1. Target: Select AWS Lambda → Choose  SecurityWatchdogAgent .


🖥️ Demo

1. Manual Schedule Run

Click Test inside the Lambda Console.
  • On the first run, the agent fetches new advisories and posts rich color-coded cards to Discord.
  • On the second run, DynamoDB state memory detects that the IDs have already been processed, and the agent outputs a green "All Systems Clear" heartbeat message to Discord.

2. Simulated AWS Event Run

Create a custom test event payload in Lambda simulating a CloudTrail API action ( AWS API Call via CloudTrail ). The agent recognizes the payload and immediately formats a specialized red alert card displaying the event name, user identity, and region.


🎯 Conclusion

With fewer than 200 lines of Python code and zero server management overhead, this autonomous agent acts as a continuous cloud monitor—delivering actionable threat briefings while staying entirely free on AWS.
Checkout  Github  for more info & projects.

Series: Lambda Series (1 article)

  1. 1
    Autonomous Cloud Security Watchdog Agent This article
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article