Skip to content
TrungCLN

AWSIntermediate

Send Security Hub and GuardDuty alerts to Teams or Slack with EventBridge and Lambda

By Cao Le Nam TrungPublished Updated 44 min read

AWS CloudHIGH, CRITICALwebhookSecurity HubGuardDutyEventBridgeLambdaSlack / Teams
Diagram drawn with the official AWS Architecture Icons.

Key results

  • The EventBridge patterns only let severe findings through: GuardDuty 8.0 reaches the target, 2.0 is filtered out; Security Hub HIGH matches, LOW and an already RESOLVED HIGH do not.
  • A Python 3.13 Lambda function runs for real in the official Lambda image, reads the webhook from a SecureString and posts the right format for both Slack (blocks) and Teams (Adaptive Card).
  • Terraform creates 11 resources; the webhook URL never lands in state thanks to the write-only value_wo argument.
  • The first call takes about 0.5 s (loading boto3, reading SSM); the next one about 4 ms because the URL is cached in memory.

What you need

  • No prior Security Hub, GuardDuty, EventBridge or Lambda knowledge: the guide explains it from scratch.
  • A Linux machine with Docker, Terraform 1.11 or later, AWS CLI v2 and jq. Setup is in the "Lab setup" guide.
  • No AWS, Slack or Teams account needed: Moto mocks the AWS APIs and a tiny webhook receiver plays the chat channel.
Time
45 min
Cost
$0 following this guide (mocked). On real AWS: GuardDuty and Security Hub CSPM have 30-day free trials, then usage-based pricing
  • AWS Security Hub CSPM
  • Amazon GuardDuty
  • Amazon EventBridge
  • AWS Lambda
  • SSM Parameter Store
  • Terraform
  • Moto

Watch the lab video

Video thumbnail: Send Security Hub and GuardDuty alerts to Teams or Slack with EventBridge and Lambda

🎬 Goes live 26 Dec 2026, 20:00 (UTC+7)

Subscribe to YouTube @trungcln to get notified

Once Security Hub and GuardDuty are on, the console fills up with hundreds of findings. The few that are truly dangerous sit among many “fix when you have time” items, and nobody watches the console all day. The usual result: the important alert gets noticed too late.

This guide builds a short path: only HIGH or CRITICAL findings are routed by EventBridge to a Lambda function, which rewrites them into one short message and posts it to a Slack or Microsoft Teams channel. Lower-severity findings stay in the console for scheduled review. Every step runs for real on a lab machine, at zero cost.

A few concepts first

Finding
A record describing something worrying: a misconfiguration, unusual behaviour, a vulnerability. Each finding has a severity, the affected resource and a workflow status.Example: A security group open to the whole internet on port 22.
Severity
How serious it is. Security Hub CSPM uses words (LOW, HIGH...), GuardDuty uses a number from 1.0 to 10.0.Example: GuardDuty 8.0 is High.
Event and event bus
Whenever an AWS service has news, it sends a JSON document called an event to an EventBridge "bus", like dropping a letter into a shared mailbox.Example: A new GuardDuty finding lands on the default bus.
Rule and event pattern
A rule is a mail-routing rule: the event pattern describes which letters it accepts, the target is where they go. Events that do not match are ignored by that rule.Example: Accept only findings with severity HIGH or CRITICAL.
AWS Lambda function
Code that AWS runs for you whenever an event arrives, with no server to manage. It stops when done and is billed per request and run time.Example: handler.py takes a finding and posts to Slack.
Webhook and SSM SecureString
A webhook is an HTTPS URL: anything POSTed to it shows up in the chat channel, so it is a secret. A SecureString is an SSM Parameter Store parameter encrypted with KMS, a good place for that kind of secret.Example: The parameter /l05/chat/webhook-url.
INFORMATIONAL0LOW1 – 39MEDIUM40 – 69HIGH70 – 89CRITICAL90 – 100Low1.0 – 3.9Medium4.0 – 6.9High7.0 – 8.9Critical9.0 – 10.0Security Hub CSPM · Severity.Label (ASFF)GuardDuty · severity (number 1.0 to 10.0)Sent to chatConsole only
The two services measure severity differently: Security Hub CSPM uses words, GuardDuty uses numbers. Think of a storm warning scale: only the top levels sound the siren, the low ones are logged for later.

This guide only pushes the two highest levels to chat. The lower levels still need fixing, but reviewing them on a schedule in the console is enough. Pushing everything to chat leads to alert fatigue: the channel gets noisy, people mute it, and the real alert is ignored along with the noise.

Architecture on real AWS

AWS Cloud · one account, one RegionSlackincoming webhookMicrosoft TeamsWorkflows webhookHIGH, CRITICAL onlyread URLHTTPS POSTSecurity Hub CSPMGuardDutyEventBridgeLambdaParameter StoreLogs2 filter rules
The animated lines show the path of one alert. EventBridge is the mailroom clerk: only urgent mail is passed to Lambda, which rewrites it short and posts it to the chat channel.
Component Name in this guide Why it is needed
EventBridge rule for Security Hub CSPM l05-securityhub-high Security Hub CSPM sends every new finding and every update to EventBridge. The rule lets only HIGH/CRITICAL, new, active findings through.
EventBridge rule for GuardDuty l05-guardduty-high GuardDuty sends findings with a numeric severity; the rule keeps 7.0 and above (High and Critical).
Lambda function l05-security-alert-chat Turns a finding with dozens of fields into a few readable lines, in the exact Slack or Teams format.
SSM parameter /l05/chat/webhook-url Holds the webhook URL as a SecureString. The function only knows the parameter name, not the URL.
Log group /aws/lambda/l05-security-alert-chat Records every send (success, HTTP status), kept for 30 days.

The lab model and how it runs

The diagram above is the architecture on real AWS. The lab rebuilds exactly that path on one Linux machine with Docker, with no AWS, Slack or Teams account. This section gives you the full picture before you type any command: what exists, what talks to what, and over which port.

Lab machine: Linux + Docker, every port bound to 127.0.0.1 onlyContainer moto · :4566lab05 folderevents, patterns, main.tfTerraformterraform applyAWS CLI (awsl) + jqput-events, receive-messageContainer l05-rulerruler.sh · Event Ruler 2.2.0EventBridgebus l05-lab + 2 real rulesSQS l05-matchedshows what got throughSSM Parameter Store/l05/chat/webhook-urlLambda, IAM, Logsconfiguration onlycurl (invoke.sh)sends a sample eventContainer l05-lambdapython:3.13 · handler.pyContainer l05-receiver127.0.0.1:8005/hookPOST :8080/2015-03-31/…GetParameterPOST JSON to the webhook:4566Not in the lab: real Security Hub, GuardDuty, Slack, Teamsruns on its own, reads events/ + patterns/
Every box is something that really runs in the lab, every line a real call with its port or environment variable. Moto plays the AWS APIs, l05-receiver plays the chat channel.

Components in the lab

Component What it is Role it plays on real AWS Created with / file
Container moto, 127.0.0.1:4566 Moto, open-source software that answers AWS APIs; data lives in memory only The EventBridge, SQS, SSM, Lambda, IAM and CloudWatch Logs APIs of one Region docker run ... motoserver/moto (step 1)
events/*.json 5 sample events, envelope copied from the AWS docs, fake data Events that Security Hub CSPM and GuardDuty send to EventBridge You create them (step 1)
patterns/*.json 2 event patterns The filters of the 2 EventBridge rules You create them (step 2)
Bus l05-lab, rule l05-gd-high, queue l05-matched A temporary test rig on Moto No real equivalent; only there to show which events get through AWS CLI awsl (step 3), deleted right after
Container l05-ruler Maven + the Event Ruler 2.2.0 library running Check.java An extra check standing in for aws events test-event-pattern ruler/ruler.sh (step 3)
lambda/handler.py The function code The Lambda function l05-security-alert-chat You write it (step 4)
main.tf Terraform configuration Creates the SSM parameter, log group, role, Lambda function, 2 rules, 2 targets and 2 permissions on the default bus terraform apply (step 5)
Container l05-lambda The official image public.ecr.aws/lambda/python:3.13, with the Runtime Interface Emulator listening on port 8080 The execution environment of the Lambda service docker run (step 6)
curl to :8080 Sends the event JSON into the function EventBridge invoking the function when a rule matches curl command (step 6)
Container l05-receiver, 127.0.0.1:8005/hook A tiny Python HTTP server that prints the JSON it receives and answers ok The Slack or Teams channel webhook receiver/receiver.py (step 6)

How the pieces connect

1. Finding createdSecurity Hub CSPM / GuardDuty2. EventBridge matchesdefault bus, rule l05-*-high3. Lambda invokedwith the event JSON4. Webhook read from SSMGetParameter, KMS decrypt5. HTTPS POSTSlack JSON or Adaptive Card6. Message in the channelSlack / TeamsSecurity Hub CSPM / GuardDuty enabledevery field in the pattern matcheslambda:InvokeFunctionfor events.amazonaws.comrole: ssm:GetParameter + kms:Decryptroute to the internet (port 443)webhook still validLab: events/*.jsonLab: rule on Moto, Event RulerLab: curl to l05-lambda :8080Lab: SSM in MotoLab: http://127.0.0.1:8005/hookLab: docker logs l05-receiverMiss one condition and the chain breaks at that hop, usually without any error on your side.
The boxes are the hops on real AWS, the small orange line is what each hop needs to work, the grey line is what plays that hop in the lab.

An alert goes through 6 hops. Each hop has one requirement; if it is missing, the chain breaks right there.

  1. Security Hub CSPM or GuardDuty creates a finding and sends a JSON event to the EventBridge default bus in the same Region. Nothing to configure for this hop beyond enabling the service. In the lab: the events/*.json files.
  2. EventBridge compares the event with each rule’s event pattern. On a match it hands the event to the rule’s target; otherwise the rule ignores it. In the lab: a real rule on Moto for GuardDuty, Event Ruler for Security Hub.
  3. The rule invokes the Lambda function, passing the whole event JSON as the event argument of lambda_handler. The function needs a resource-based policy that allows events.amazonaws.com to call lambda:InvokeFunction (in Terraform: aws_lambda_permission). In the lab: curl POSTs to http://127.0.0.1:8080/2015-03-31/functions/function/invocations.
  4. The function reads the webhook from SSM: it takes the parameter name from the WEBHOOK_PARAM environment variable, calls ssm:GetParameter with WithDecryption, and SSM asks KMS to decrypt. The function role needs ssm:GetParameter and kms:Decrypt. In the lab: boto3 calls Moto’s SSM thanks to AWS_ENDPOINT_URL_SSM=http://127.0.0.1:4566.
  5. The function sends an HTTPS POST with the message JSON to the webhook URL. It needs a route to the internet: a function that is not attached to a VPC has one; a function attached to a VPC must go through a NAT gateway. In the lab: POST to http://127.0.0.1:8005/hook (both containers share the machine’s network).
  6. Slack or Teams shows the message in the channel. In the lab: docker logs l05-receiver prints the exact JSON received.

Alongside hop 5, the function prints one JSON log line. On AWS it lands in the log group /aws/lambda/l05-security-alert-chat (the role needs logs:CreateLogStream and logs:PutLogEvents); in the lab you read it with docker logs l05-lambda.

What is prepared

After the steps, the lab folder holds exactly these files:

lab05/
lab05/
├── events/
│ ├── sh-high.json Security Hub CSPM, HIGH, NEW, ACTIVE → must alert
│ ├── sh-low.json Security Hub CSPM, LOW → no alert
│ ├── sh-high-resolved.json Security Hub CSPM, HIGH but RESOLVED → no alert
│ ├── gd-high.json GuardDuty, severity 8.0 → must alert
│ └── gd-low.json GuardDuty, severity 2.0 → no alert
├── patterns/
│ ├── securityhub-high.json HIGH/CRITICAL + NEW + ACTIVE
│ └── guardduty-high.json severity >= 7
├── lambda/handler.py Lambda function (Python 3.13, standard library)
├── receiver/receiver.py fake webhook receiver, port 8005
├── ruler/ Check.java + pom.xml + ruler.sh (Event Ruler)
└── main.tf Terraform for the AWS side (11 resources)

The lab folder also has a few short scripts that wrap the exact commands from this guide (put-event.sh, moto-filter.sh, moto-clean.sh, run-local.sh, invoke.sh) so reruns are quick; the guide still shows every command in full.

What is real and what is mocked:

In the lab Real or mocked On real AWS, Slack, Teams
AWS APIs on 127.0.0.1:4566 Mocked (Moto) The Region’s AWS endpoints, for example events.ap-southeast-1.amazonaws.com
test keys Fake Permissions of an IAM role or an SSO user
events/*.json Fake (real envelope from the docs) Findings created by Security Hub CSPM and GuardDuty
Rules, patterns, PutEvents Real API calls, Moto’s matcher EventBridge
Event Ruler Real (AWS library running locally) Not used; run aws events test-event-pattern instead
Terraform apply Real, against Moto Identical, minus the endpoints block and fake keys
Function in l05-lambda Real: same image, same runtime, same code The Lambda service invoking the function
curl to port 8080 Stands in for EventBridge invoking the function EventBridge invokes it when a rule matches
l05-receiver Fake (stands in for the chat channel) A Slack webhook (https://hooks.slack.com/services/...) or a Teams Workflows webhook
docker logs Real CloudWatch Logs

The whole run at a glance

The full guide in order, with the result you should see at each step:

  1. Start Moto, create the 5 sample events (step 1). Result: docker ps lists the moto container; events/ holds 5 files.
  2. Write the 2 event patterns (step 2). Result: 2 files in patterns/.
  3. Test the patterns (step 3). Result: the l05-matched queue only holds the GuardDuty severity 8 message; Event Ruler prints true, false, false for the 3 Security Hub events and true, false for GuardDuty.
  4. Write the function handler.py (step 4).
  5. Build the AWS side with Terraform (step 5). Result: Apply complete! Resources: 11 added; grep for the webhook URL in terraform.tfstate prints 0.
  6. Start l05-receiver and l05-lambda, invoke the function (step 6). Result: the HIGH event returns {"sent": 1, "http_status": 200} and the receiver prints one Slack message; the LOW event returns {"sent": 0}; switch to Teams and the receiver prints an Adaptive Card.
  7. Connect a real channel (step 7, once you have an AWS account and a chat channel). Result: the message appears in the channel.
  8. Clean up. Result: no l05-* containers left, Terraform reports 11 destroyed.

Step 1: Prepare Moto and the sample events

What you are doing: start the AWS mock on your machine, create the lab folder and the sample event files. The samples follow the exact envelope from the AWS docs; the data is fake.

Terminal window
docker run -d --name moto -p 127.0.0.1:4566:5000 motoserver/moto
export AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test AWS_DEFAULT_REGION=us-east-1 # fake keys
alias awsl='aws --endpoint-url http://localhost:4566'
mkdir -p lab05/{events,patterns,lambda,receiver} && cd lab05
Command Meaning Why
-p 127.0.0.1:4566:5000 Opens port 4566 on your machine, wired to Moto Bound to 127.0.0.1 only, so other machines on the network cannot reach it.
export AWS_ACCESS_KEY_ID=test ... Fake access keys The AWS CLI insists on keys. Moto accepts any. Never use real keys here.
alias awsl=... awsl is the AWS CLI pointed at Moto No risk of hitting a real account by mistake.

The Security Hub CSPM event, file events/sh-high.json:

events/sh-high.json
{
"version": "0",
"id": "11111111-2222-3333-4444-000000000001",
"detail-type": "Security Hub Findings - Imported",
"source": "aws.securityhub",
"account": "111122223333",
"time": "2026-12-02T03:15:00Z",
"region": "ap-southeast-1",
"resources": ["arn:aws:securityhub:ap-southeast-1:111122223333:finding/lab-1"],
"detail": {
"findings": [
{
"SchemaVersion": "2018-10-08",
"Id": "arn:aws:securityhub:ap-southeast-1:111122223333:finding/lab-1",
"ProductArn": "arn:aws:securityhub:ap-southeast-1::product/aws/securityhub",
"AwsAccountId": "111122223333",
"Region": "ap-southeast-1",
"Severity": { "Label": "HIGH", "Normalized": 70 },
"Title": "Sample: security group allows 0.0.0.0/0 on port 22",
"Resources": [
{ "Type": "AwsEc2SecurityGroup", "Id": "arn:aws:ec2:ap-southeast-1:111122223333:security-group/sg-0123456789abcdef0" }
],
"Workflow": { "Status": "NEW" },
"RecordState": "ACTIVE"
}
]
}
}
Line Meaning Why it matters
"detail-type": "Security Hub Findings - Imported" The event type Security Hub CSPM uses for new and updated findings The rule filters on this exact string. Each event carries exactly one finding.
"detail": { "findings": [ ... ] } The finding sits inside an array The pattern has to reach into this array; this is what Moto cannot do (step 3).
Severity.Label Severity as a word: INFORMATIONAL, LOW, MEDIUM, HIGH, CRITICAL Filter on Label. AWS marks the Normalized field (0–100) as deprecated.
Workflow.Status Workflow status: NEW, NOTIFIED, RESOLVED, SUPPRESSED Only alert on NEW findings nobody has picked up yet.
RecordState ACTIVE or ARCHIVED ARCHIVED means the finding is no longer relevant; alerting on it is noise.
111122223333 The sample account ID used in the AWS docs Never put a real account ID in sample files.

The set also has sh-low.json (LOW) and sh-high-resolved.json (HIGH but already RESOLVED). GuardDuty events are different: detail is one object, not an array, and the severity is a number:

events/gd-high.json (detail part)
{
"detail-type": "GuardDuty Finding",
"source": "aws.guardduty",
"detail": {
"accountId": "111122223333",
"region": "ap-southeast-1",
"type": "Sample:EC2/HighSeverityLab",
"severity": 8.0,
"title": "Sample: EC2 instance talking to a known bad IP",
"resource": { "resourceType": "Instance", "instanceDetails": { "instanceId": "i-0123456789abcdef0" } }
}
}

gd-low.json is identical except for severity 2.0. The finding type starts with Sample: so nobody mistakes it for a real one.

Check before moving on to step 2 (real output from the lab machine):

Terminal window
docker ps --filter name=^moto$ --format "{{.Names}} {{.Ports}}"
ls events
moto 127.0.0.1:4566->5000/tcp
gd-high.json
gd-low.json
sh-high-resolved.json
sh-high.json
sh-low.json

How to read the result: the first line says the moto container is running and port 4566 is open on 127.0.0.1 only. The five file names are the five sample events: three from Security Hub CSPM (sh-*), two from GuardDuty (gd-*). If the moto line is missing, read the error with docker logs moto.

Step 2: Write the event patterns

What you are doing: write two “mail-routing rules”, one JSON file each.

patterns/securityhub-high.json
{
"source": ["aws.securityhub"],
"detail-type": ["Security Hub Findings - Imported"],
"detail": {
"findings": {
"Severity": { "Label": ["HIGH", "CRITICAL"] },
"Workflow": { "Status": ["NEW"] },
"RecordState": ["ACTIVE"]
}
}
}
Line Meaning Why it is set this way
"source", "detail-type" Only Security Hub CSPM finding events Without these the rule inspects every event on the bus and can catch other types (insight results, for example).
"findings": { ... } Look inside each element of the findings array EventBridge matches arrays by intersection: it is enough for the event value to be in the pattern list.
"Label": ["HIGH", "CRITICAL"] HIGH or CRITICAL Several values in one field are an OR. Add MEDIUM here and the channel gets noisy fast.
"Status": ["NEW"] Only findings nobody has picked up Security Hub CSPM re-sends an event every time a finding is updated; a NOTIFIED or RESOLVED finding needs no second alert.
"RecordState": ["ACTIVE"] Only findings still in effect Different fields are combined with AND: miss one condition and there is no match.
patterns/guardduty-high.json
{
"source": ["aws.guardduty"],
"detail-type": ["GuardDuty Finding"],
"detail": { "severity": [{ "numeric": [">=", 7] }] }
}
Line Meaning Why it is set this way
"detail-type": ["GuardDuty Finding"] The event type GuardDuty uses for findings GuardDuty sends new findings in near real time; repeat occurrences are aggregated and sent on a schedule (every 6 hours by default).
"numeric": [">=", 7] Severity 7.0 and above From the GuardDuty table: High is 7.0–8.9, Critical is 9.0–10.0. One numeric condition is shorter than listing every value.

Check the syntax of both files (one stray comma and EventBridge rejects the whole rule):

Terminal window
jq -c . patterns/*.json >/dev/null && echo "patterns OK"
patterns OK

How to read the result: if jq can parse both files it prints patterns OK. A broken file makes jq print the file name and line number, and no OK. Valid syntax does not mean correct filtering; step 3 checks that.

Security Hub · HIGHNEW · ACTIVESecurity Hub · LOWNEW · ACTIVESecurity Hub · HIGHRESOLVED · ACTIVEGuardDuty · 8.0High levelGuardDuty · 2.0Low levelMatches every condition?AND across fieldsLambdaIncoming eventsEvent patternTo Lambda✕✕✕
An event pattern works like a ticket inspector: the event must match every field listed in the pattern (AND), while inside one field it only has to match one value of the list (OR). Miss one condition and it stays at the door.

Step 3: Test the patterns before wiring up Lambda

What you are doing: check that the patterns catch severe events and skip mild ones, before writing a single line of code. On real AWS the quickest way is the TestEventPattern API:

Terminal window
aws events test-event-pattern --event-pattern file://patterns/guardduty-high.json --event file://events/gd-high.json

On real AWS the command returns {"Result": true} or {"Result": false}; the event must include id, account, source, time, region, resources and detail-type. Moto does not implement this API: the command exits without an error but prints nothing (first line of the screenshot below). So the guide uses two other methods, both run for real.

Method 1, GuardDuty through PutEvents: create a test bus l05-lab, a rule with the GuardDuty pattern and an SQS queue l05-matched as its target. Send the 8.0 and 2.0 events with PutEvents, then see what the queue received.

Terminal window
awsl events create-event-bus --name l05-lab
Q=$(awsl sqs create-queue --queue-name l05-matched --query QueueUrl --output text)
QA=$(awsl sqs get-queue-attributes --queue-url "$Q" --attribute-names QueueArn --query Attributes.QueueArn --output text)
awsl events put-rule --name l05-gd-high --event-bus-name l05-lab --event-pattern file://patterns/guardduty-high.json
awsl events put-targets --rule l05-gd-high --event-bus-name l05-lab --targets "Id=matched,Arn=$QA"
for f in events/gd-high.json events/gd-low.json; do
awsl events put-events --entries "$(jq -c '[{EventBusName:"l05-lab", Source:.source, DetailType:."detail-type", Detail:(.detail|tojson)}]' "$f")"
done
awsl sqs receive-message --queue-url "$Q" --max-number-of-messages 10 --query "Messages[].Body" --output text \
| jq -c '{source, severity: .detail.severity, title: .detail.title}'
Line Meaning Why
create-event-bus --name l05-lab A separate bus for the test Keeps it apart from the default bus, where the real rules (step 5) target a Lambda function Moto cannot invoke.
SQS queue as target Events that match the pattern are copied into the queue Reading the queue shows exactly which events got through.
jq ... Detail:(.detail|tojson) Turns the event file into PutEvents input The API expects Detail as a JSON string, not an object.
Terminal: awsl events test-event-pattern on Moto prints nothing and exit=0; rule l05-gd-high is created on bus l05-lab; two GuardDuty events with severity 8.0 and 2.0 are sent, both with FailedEntryCount 0; queue l05-matched holds a single message with source aws.guardduty, severity 8, title Sample: EC2 instance talking to a known bad IP
Real run on the lab machine: Moto does not answer TestEventPattern, but the PutEvents → rule → SQS path works. Two events sent, the queue only received the severity 8 one.

How to read the result:

  • exit=0 with no Result line: Moto accepted the call but does not implement it. Do not read it as “no match”.
  • The two 0 lines after each send are FailedEntryCount: both events reached the bus.
  • The queue holds one message, "severity":8. The 2.0 event was ignored by the rule. The GuardDuty pattern is right.

Method 2, Security Hub with Event Ruler: for the Security Hub pattern, Moto does not reach into the findings[] array, so it skips even the HIGH event (a test run left the queue empty). That is a Moto limitation, not an EventBridge one: the EventBridge docs describe array matching explicitly. To get a real true/false for this pattern, the guide uses Event Ruler, an open-source Java library from AWS that matches rules against JSON events (github.com/aws/event-ruler), through its Ruler.matchesRule(event, rule) method.

Terminal window
./ruler/ruler.sh patterns/securityhub-high.json events/sh-high.json events/sh-low.json events/sh-high-resolved.json
./ruler/ruler.sh patterns/guardduty-high.json events/gd-high.json events/gd-low.json

ruler.sh runs a Maven container, downloads software.amazon.event.ruler:event-ruler:2.2.0 and runs a 10-line Java program, Check.java, that prints the result for each file.

Terminal: the Security Hub and GuardDuty patterns printed with jq; Event Ruler returns sh-high.json true, sh-low.json false, sh-high-resolved.json false; gd-high.json true, gd-low.json false
Real run: the Security Hub pattern only matches the new HIGH finding; the LOW finding and the RESOLVED HIGH finding are both rejected. The GuardDuty pattern agrees with method 1.

How to read the result: sh-high.json -> true is an event that will reach Lambda. sh-low.json -> false because of the severity; sh-high-resolved.json -> false even though it is HIGH, because Workflow.Status is RESOLVED. The two GuardDuty lines match method 1.

Step 4: Write the Lambda function

What you are doing: write a function that takes the event, extracts the key facts, builds a Slack or Teams message and POSTs it to the webhook. It uses only the Python standard library; boto3 (the AWS SDK for Python) ships with the Lambda runtime, so there is nothing extra to package.

lambda/handler.py
"""Security Hub CSPM / GuardDuty finding -> short Slack or Microsoft Teams message.
Standard library only (json, os, urllib). boto3 ships with the Lambda Python runtime
and is imported only to read the webhook URL from SSM Parameter Store.
"""
import json
import os
import urllib.request
WEBHOOK_PARAM = os.environ.get("WEBHOOK_PARAM", "") # SSM parameter name (SecureString)
CHAT_FORMAT = os.environ.get("CHAT_FORMAT", "slack") # slack | teams
MAX_ITEMS = 5 # list at most 5 findings per message, the rest become "+N more"
_webhook_cache = None # reused across invocations of the same execution environment
def webhook_url():
"""Webhook URL from SSM SecureString, or WEBHOOK_URL for local tests only."""
global _webhook_cache
if _webhook_cache:
return _webhook_cache
if os.environ.get("WEBHOOK_URL"):
_webhook_cache = os.environ["WEBHOOK_URL"]
else:
import boto3 # included in the Lambda Python runtime
ssm = boto3.client("ssm")
resp = ssm.get_parameter(Name=WEBHOOK_PARAM, WithDecryption=True)
_webhook_cache = resp["Parameter"]["Value"]
return _webhook_cache
def console_link(service, region):
if service == "guardduty":
return f"https://{region}.console.aws.amazon.com/guardduty/home?region={region}#/findings"
return f"https://{region}.console.aws.amazon.com/securityhub/home?region={region}#/findings"
def guardduty_label(score):
# GuardDuty levels: Low 1.0-3.9, Medium 4.0-6.9, High 7.0-8.9, Critical 9.0-10.0
if score >= 9:
return "CRITICAL"
if score >= 7:
return "HIGH"
if score >= 4:
return "MEDIUM"
return "LOW"
def to_alerts(event):
"""Turn an EventBridge event into a list of short alerts."""
region = event.get("region", "?")
if event.get("source") == "aws.guardduty":
d = event["detail"]
res = d.get("resource", {})
inst = res.get("instanceDetails", {}).get("instanceId", "")
return [{
"service": "GuardDuty",
"title": d.get("title", d.get("type", "?")),
"severity": guardduty_label(float(d.get("severity", 0))),
"account": d.get("accountId", event.get("account", "?")),
"region": d.get("region", region),
"resource": f"{res.get('resourceType', '?')} {inst}".strip(),
"id": d.get("id", "?"),
"link": console_link("guardduty", region),
}]
alerts = []
for f in event.get("detail", {}).get("findings", []):
label = f.get("Severity", {}).get("Label", "?")
# Re-check every finding: only HIGH/CRITICAL, NEW and ACTIVE
if label not in ("HIGH", "CRITICAL"):
continue
if f.get("Workflow", {}).get("Status") != "NEW" or f.get("RecordState") != "ACTIVE":
continue
res = (f.get("Resources") or [{}])[0]
alerts.append({
"service": "Security Hub",
"title": f.get("Title", "?"),
"severity": label,
"account": f.get("AwsAccountId", event.get("account", "?")),
"region": f.get("Region", region),
"resource": f"{res.get('Type', '?')} {res.get('Id', '')}".strip(),
"id": f.get("Id", "?"),
"link": console_link("securityhub", region),
})
return alerts
def slack_payload(alerts):
a = alerts[0]
more = f" (+{len(alerts) - 1} more)" if len(alerts) > 1 else ""
text = f"[{a['severity']}] {a['service']}: {a['title']}{more}"
blocks = [{"type": "header", "text": {"type": "plain_text", "text": text[:150]}}]
for x in alerts[:MAX_ITEMS]:
blocks.append({"type": "section", "fields": [
{"type": "mrkdwn", "text": f"*Severity*\n{x['severity']}"},
{"type": "mrkdwn", "text": f"*Account / Region*\n{x['account']} / {x['region']}"},
{"type": "mrkdwn", "text": f"*Resource*\n{x['resource']}"},
{"type": "mrkdwn", "text": f"*Finding*\n<{x['link']}|Open in console>"},
]})
return {"text": text, "blocks": blocks}
def teams_payload(alerts):
a = alerts[0]
more = f" (+{len(alerts) - 1} more)" if len(alerts) > 1 else ""
body = [{"type": "TextBlock", "size": "Large", "weight": "Bolder", "wrap": True,
"text": f"[{a['severity']}] {a['service']}: {a['title']}{more}"}]
for x in alerts[:MAX_ITEMS]:
body.append({"type": "FactSet", "facts": [
{"title": "Severity", "value": x["severity"]},
{"title": "Account / Region", "value": f"{x['account']} / {x['region']}"},
{"title": "Resource", "value": x["resource"]},
]})
card = {"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard", "version": "1.2", "body": body,
"actions": [{"type": "Action.OpenUrl", "title": "Open in console", "url": a["link"]}]}
return {"type": "message", "attachments": [{
"contentType": "application/vnd.microsoft.card.adaptive", "contentUrl": None, "content": card}]}
def post(url, payload):
req = urllib.request.Request(url, data=json.dumps(payload).encode(),
headers={"Content-Type": "application/json"}, method="POST")
with urllib.request.urlopen(req, timeout=5) as r: # short timeout: a hung webhook must not hold the function
return r.status
def lambda_handler(event, context):
alerts = to_alerts(event)
if not alerts:
print(json.dumps({"sent": 0, "reason": "no HIGH/CRITICAL NEW ACTIVE finding"}))
return {"sent": 0}
payload = teams_payload(alerts) if CHAT_FORMAT == "teams" else slack_payload(alerts)
status = post(webhook_url(), payload)
print(json.dumps({"sent": len(alerts), "format": CHAT_FORMAT, "http_status": status}))
return {"sent": len(alerts), "http_status": status}
Line Meaning Why it is set this way
WEBHOOK_PARAM An environment variable holding only the SSM parameter name Anyone who views the function configuration sees a name, not the webhook URL. AWS recommends not keeping sensitive values in environment variables.
_webhook_cache Keeps the URL in memory after the first read Lambda reuses the execution environment for later invocations, so SSM is not called every time. Measured in step 6: about 0.5 s the first time, about 4 ms after that.
WithDecryption=True Asks SSM to decrypt the SecureString Without it you get the encrypted blob back, and POSTing to it fails.
os.environ.get("WEBHOOK_URL") Shortcut for local tests Local testing only. Do not set it on AWS.
Loop re-checking Label, Status, RecordState A second filter in code If someone loosens the rule later, the channel still does not get flooded.
guardduty_label Maps 1.0–10.0 to a word Messages from both sources look the same; readers do not need to memorise the number table.
console_link Link to the findings list One click takes the reader to the right service and Region. The message is a pointer; the details live in the console.
text in slack_payload Summary line next to blocks Slack returns no_text when the payload has no text; blocks is extra layout on top.
teams_payload Adaptive Card wrapped in attachments The envelope Microsoft documents for Workflows webhooks (step 7).
timeout=5 Wait at most 5 seconds for the webhook A hung webhook stops the function early instead of running to its maximum time and costing money.
print(json.dumps(...)) One JSON log line Never print the webhook URL to logs. The log only has the count, format and HTTP status.

Check that the file compiles before packaging it:

Terminal window
python3 -m py_compile lambda/handler.py && echo "handler OK"
handler OK

How to read the result: handler OK means Python can read the file with no syntax error. Logic errors (a wrong field name, a wrong message shape) only show up when the function really runs in step 6.

Step 5: Build the AWS side with Terraform

What you are doing: describe the whole AWS side in main.tf: the SSM parameter, the log group, the role, the function, two rules and the permission for EventBridge to invoke the function. Then let Terraform create it on Moto.

Part 1: Provider and secret variable

main.tf (part 1)
terraform {
required_version = ">= 1.11" # write-only value_wo needs Terraform 1.11+
required_providers {
aws = { source = "hashicorp/aws", version = "~> 6.0" }
archive = { source = "hashicorp/archive", version = "~> 2.0" }
}
}
provider "aws" {
region = "us-east-1"
access_key = "test"
secret_key = "test"
skip_credentials_validation = true
skip_metadata_api_check = true
skip_requesting_account_id = true
endpoints {
events = "http://localhost:4566"
lambda = "http://localhost:4566"
iam = "http://localhost:4566"
ssm = "http://localhost:4566"
sts = "http://localhost:4566"
logs = "http://localhost:4566"
}
}
variable "webhook_url" {
type = string
sensitive = true
ephemeral = true # never written to plan/state; pass it with TF_VAR_webhook_url
}
variable "chat_format" {
type = string
default = "slack" # slack | teams
}
Line Meaning Why it is set this way
required_version = ">= 1.11" Needs Terraform 1.11 or later The write-only value_wo argument in part 2 exists from Terraform 1.11.
access_key = "test", the skip_* lines, endpoints Fake keys and every API pointed at Moto Lab only. Remove all three for real AWS.
sensitive = true Terraform masks the value in its output The webhook URL does not show up in plan output.
ephemeral = true A transient variable, never saved in plan or state You pass the URL at run time (TF_VAR_webhook_url) instead of writing it in any file.

Part 2: SSM parameter, log group and least-privilege role

main.tf (part 2)
resource "aws_ssm_parameter" "webhook" {
name = "/l05/chat/webhook-url"
type = "SecureString"
value_wo = var.webhook_url # write-only: never stored in state
value_wo_version = 1 # bump this number to push a new URL
}
resource "aws_cloudwatch_log_group" "fn" {
name = "/aws/lambda/l05-security-alert-chat"
retention_in_days = 30
}
data "aws_iam_policy_document" "assume" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["lambda.amazonaws.com"]
}
}
}
resource "aws_iam_role" "fn" {
name = "l05-security-alert-chat"
assume_role_policy = data.aws_iam_policy_document.assume.json
}
data "aws_iam_policy_document" "fn" {
statement {
actions = ["logs:CreateLogStream", "logs:PutLogEvents"]
resources = ["${aws_cloudwatch_log_group.fn.arn}:*"]
}
statement {
actions = ["ssm:GetParameter"]
resources = [aws_ssm_parameter.webhook.arn]
}
# Decrypting a SecureString needs kms:Decrypt; the encryption context pins it to one parameter.
# With a customer managed key, replace "*" with that key ARN.
statement {
actions = ["kms:Decrypt"]
resources = ["*"]
condition {
test = "StringEquals"
variable = "kms:EncryptionContext:PARAMETER_ARN"
values = [aws_ssm_parameter.webhook.arn]
}
}
}
resource "aws_iam_role_policy" "fn" {
name = "least-privilege"
role = aws_iam_role.fn.id
policy = data.aws_iam_policy_document.fn.json
}
handler.py / environment variableWEBHOOK_URL=https://...Git repoanyone who clones ittfstatestored as plain textConsoleanyone viewing confighandler.pyonly knows the parameter NAMEssm:GetParameterLambda roleSecureStringHard-coded URLStored in Parameter Store
A webhook URL is a key to the meeting room: whoever holds it can walk in and talk. Do not tape the key to the door (code, environment variables); lock it in a safe (Parameter Store) and give the safe combination to exactly one person (the Lambda role).
Line Meaning Why it is set this way
type = "SecureString" The value is encrypted with KMS Without a key ID, Parameter Store uses the AWS managed key with the alias aws/ssm. Standard parameters have no additional charge.
value_wo A write-only value The provider docs state that write-only values are never stored in state. With a plain value, the webhook URL would sit in terraform.tfstate.
value_wo_version = 1 A version number for the value Terraform cannot compare a value it does not store. To change the webhook, bump this number so Terraform writes the new value.
retention_in_days = 30 Logs kept for 30 days By default logs never expire and keep costing storage. Creating the log group up front also means the function does not need logs:CreateLogGroup.
identifiers = ["lambda.amazonaws.com"] Only the Lambda service can assume this role The role cannot be used by another service or a person.
resources = [aws_ssm_parameter.webhook.arn] ssm:GetParameter on exactly one parameter Least privilege: this function cannot read any other secret in the account.
kms:Decrypt + kms:EncryptionContext:PARAMETER_ARN Decrypt only while reading this parameter Parameter Store docs: decrypting a SecureString needs kms:Decrypt; every encryption carries the parameter ARN as context, and this condition pins the permission to one parameter.

Part 3: Function, rules and invoke permission

main.tf (part 3)
data "archive_file" "fn" {
type = "zip"
source_file = "${path.module}/lambda/handler.py"
output_path = "${path.module}/build/handler.zip"
}
resource "aws_lambda_function" "fn" {
function_name = "l05-security-alert-chat"
role = aws_iam_role.fn.arn
runtime = "python3.13"
handler = "handler.lambda_handler"
filename = data.archive_file.fn.output_path
source_code_hash = data.archive_file.fn.output_base64sha256
timeout = 10
memory_size = 128
environment {
variables = {
WEBHOOK_PARAM = aws_ssm_parameter.webhook.name
CHAT_FORMAT = var.chat_format
}
}
depends_on = [aws_iam_role_policy.fn, aws_cloudwatch_log_group.fn]
}
resource "aws_cloudwatch_event_rule" "securityhub_high" {
name = "l05-securityhub-high"
description = "Security Hub CSPM findings HIGH/CRITICAL, NEW, ACTIVE"
event_pattern = file("${path.module}/patterns/securityhub-high.json")
}
resource "aws_cloudwatch_event_rule" "guardduty_high" {
name = "l05-guardduty-high"
description = "GuardDuty findings severity >= 7 (High, Critical)"
event_pattern = file("${path.module}/patterns/guardduty-high.json")
}
locals {
rules = {
securityhub = aws_cloudwatch_event_rule.securityhub_high
guardduty = aws_cloudwatch_event_rule.guardduty_high
}
}
resource "aws_cloudwatch_event_target" "fn" {
for_each = local.rules
rule = each.value.name
arn = aws_lambda_function.fn.arn
}
resource "aws_lambda_permission" "events" {
for_each = local.rules
statement_id = "allow-eventbridge-${each.key}"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.fn.function_name
principal = "events.amazonaws.com"
source_arn = each.value.arn
}
output "function_name" { value = aws_lambda_function.fn.function_name }
output "parameter_name" { value = aws_ssm_parameter.webhook.name }
output "rule_arns" { value = { for k, r in local.rules : k => r.arn } }
Line Meaning Why it is set this way
archive_file Zips handler.py The function only uses the standard library and the bundled boto3, so the zip holds one file and there is no install step.
runtime = "python3.13" Runs on Python 3.13 Lambda currently supports python3.12 through python3.15; the guide uses 3.13 and tests with the matching python:3.13 image.
source_code_hash Fingerprint of the zip Change the code and the fingerprint changes, so Terraform knows to update the function.
timeout = 10 The function runs for at most 10 seconds Enough for one SSM read and one POST (at most 5 seconds), without letting it hang.
event_pattern = file(...) The exact pattern files tested in step 3 What goes to AWS is identical to what you tested; no copy-paste.
No event_bus_name on the rules The rules live on the default bus Security Hub CSPM and GuardDuty send findings to the default bus.
principal = "events.amazonaws.com" Lets EventBridge invoke the function Without it the rule matches but EventBridge cannot call Lambda.
source_arn = each.value.arn Only these two rules may invoke it Without this condition, any rule in the account pointed at the function could invoke it.

Create the resources, passing the webhook URL as an environment variable. In the lab, the URL is the fake receiver from step 6:

Terminal window
terraform init
export TF_VAR_webhook_url=http://127.0.0.1:8005/hook
terraform apply -auto-approve
grep -c '127.0.0.1:8005' terraform.tfstate
awsl ssm get-parameter --name /l05/chat/webhook-url --with-decryption --query "Parameter.[Type,Value]" --output text
Terminal: terraform apply ends with Apply complete! Resources: 11 added, 0 changed, 0 destroyed, outputs function_name l05-security-alert-chat, parameter_name /l05/chat/webhook-url and two rule ARNs; grep -c on terraform.tfstate prints 0; get-parameter prints SecureString and http://127.0.0.1:8005/hook
Real run on Moto: 11 resources created. The webhook URL is in Parameter Store but not in terraform.tfstate (grep counts 0 lines).

How to read the result:

  • Resources: 11 added: 1 parameter, 1 log group, 1 role, 1 policy, 1 function, 2 rules, 2 targets, 2 permissions.
  • grep -c prints 0: the state file does not contain the webhook URL. That is value_wo plus the ephemeral variable at work.
  • get-parameter prints SecureString and the URL: the parameter exists, and only someone allowed to read (and decrypt) it sees the value.

Step 6: Run the function for real and inspect the Slack and Teams payloads

What you are doing: run handler.py inside the official Lambda image public.ecr.aws/lambda/python:3.13. The image ships the Runtime Interface Emulator, a program that mimics how Lambda invokes a function, so you can call the function with curl exactly as Lambda would. The function reads the webhook from the SSM parameter you just created on Moto, then POSTs to a fake receiver that prints the JSON it gets.

receiver/receiver.py
"""Fake webhook receiver (stands in for Slack/Teams). Prints the JSON it gets and answers "ok" like Slack."""
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
def gon(v, lui=0):
"""Indented JSON, but short objects/arrays (<= 110 chars) stay on one line."""
phang = json.dumps(v, ensure_ascii=False)
if len(phang) + lui <= 110 or not isinstance(v, (dict, list)):
return phang
pad = " " * (lui + 2)
if isinstance(v, dict):
dong = [f'{pad}{json.dumps(k)}: {gon(x, lui + 2)}' for k, x in v.items()]
return "{\n" + ",\n".join(dong) + "\n" + " " * lui + "}"
dong = [pad + gon(x, lui + 2) for x in v]
return "[\n" + ",\n".join(dong) + "\n" + " " * lui + "]"
class Hook(BaseHTTPRequestHandler):
def do_POST(self):
body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
print(f"== POST {self.path} ({len(body)} bytes, {self.headers.get('Content-Type')})", flush=True)
print(gon(json.loads(body)), flush=True)
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write(b"ok")
def log_message(self, *args): # silence the default access log
pass
HTTPServer(("127.0.0.1", 8005), Hook).serve_forever()

Start both containers and invoke the function with two sample events:

Terminal window
docker run -d --name l05-receiver --network host -v "$PWD/receiver:/app:ro" python:3.13-slim \
python -u /app/receiver.py
docker run -d --name l05-lambda --network host -v "$PWD/lambda:/var/task:ro" \
-e AWS_ACCESS_KEY_ID=test -e AWS_SECRET_ACCESS_KEY=test -e AWS_REGION=us-east-1 -e AWS_DEFAULT_REGION=us-east-1 \
-e AWS_ENDPOINT_URL_SSM=http://127.0.0.1:4566 \
-e WEBHOOK_PARAM=/l05/chat/webhook-url -e CHAT_FORMAT=slack \
public.ecr.aws/lambda/python:3.13 handler.lambda_handler
curl -s -X POST http://127.0.0.1:8080/2015-03-31/functions/function/invocations -d @events/sh-high.json
curl -s -X POST http://127.0.0.1:8080/2015-03-31/functions/function/invocations -d @events/sh-low.json
docker logs l05-receiver
Parameter Meaning Why
--network host The container shares the machine’s network Moto only listens on 127.0.0.1:4566; a container on its own network could not reach it.
-v "$PWD/lambda:/var/task:ro" Mounts the code folder at /var/task, read-only /var/task is where the Lambda image looks for code, just like on AWS.
AWS_ENDPOINT_URL_SSM boto3 calls SSM on Moto instead of AWS The function reads the parameter Terraform just created, without code changes. Do not set this on AWS.
AWS_DEFAULT_REGION Region for boto3 Without it the first call fails with NoRegionError (it happened while building this lab). On AWS, Lambda sets the Region for you.
handler.lambda_handler File name and function name Same as the handler field in Terraform.
port 8080, path /2015-03-31/functions/function/invocations The Runtime Interface Emulator endpoint The Lambda docs use this exact path to test images locally (usually mapped to port 9000; with the host network it is 8080).
Terminal: run-local.sh slack starts l05-lambda and l05-receiver; invoking sh-high.json returns sent 1, http_status 200; invoking sh-low.json returns sent 0; the l05-receiver log shows one POST /hook application/json with text [HIGH] Security Hub: Sample: security group allows 0.0.0.0/0 on port 22 and blocks containing a header and a section with the fields Severity HIGH, Account / Region 111122223333 / ap-southeast-1, Resource AwsEc2SecurityGroup, Finding Open in console
Real run: the HIGH event produces exactly one Slack message (text + blocks), the LOW event sends nothing. This is the JSON printed by the fake receiver, not a Slack screenshot.

How to read the result:

  • {"sent": 1, "http_status": 200}: the function read the webhook from SSM, sent one message, and the receiver answered 200.
  • {"sent": 0} for sh-low.json: the second filter in code dropped the LOW finding, no POST at all.
  • In the receiver log: text is the summary line, blocks is the richer layout (title, four fields, console link).

Switch to Teams: restart the l05-lambda container with -e CHAT_FORMAT=teams (in the lab folder: ./run-local.sh teams) and invoke it with the GuardDuty event:

Terminal: run-local.sh teams; invoking gd-high.json returns sent 1, http_status 200; the receiver prints JSON with type message and attachments whose contentType is application/vnd.microsoft.card.adaptive and whose content is an AdaptiveCard version 1.2 with a TextBlock [HIGH] GuardDuty: Sample: EC2 instance talking to a known bad IP, a FactSet with Severity HIGH, Account / Region, Resource Instance i-0123456789abcdef0, and an Action.OpenUrl Open in console
Real run: same function, a different CHAT_FORMAT, and it sends an Adaptive Card in the Teams Workflows webhook envelope. The GuardDuty 8.0 finding is labelled HIGH.

How to read the result: the outer {"type": "message", "attachments": [...]} and the contentType application/vnd.microsoft.card.adaptive are what Teams Workflows needs; the card itself sits in content. "version": "1.2" matches the example in Microsoft’s docs.

Invoke the function twice in a row and look at its own log (the REPORT lines come from the Runtime Interface Emulator; the RequestId values are shortened):

Terminal window
docker logs l05-lambda 2>&1 | grep -E "^\{|REPORT"
{"sent": 1, "format": "slack", "http_status": 200}
REPORT RequestId: … Init Duration: 0.07 ms Duration: 508.38 ms Billed Duration: 509 ms Memory Size: 3008 MB Max Memory Used: 3008 MB
{"sent": 1, "format": "slack", "http_status": 200}
REPORT RequestId: … Duration: 4.07 ms Billed Duration: 5 ms Memory Size: 3008 MB Max Memory Used: 3008 MB

How to read the result: the first call shows Duration: 508.38 ms because the function loads boto3 and calls SSM; the second shows 4.07 ms because the URL is already in _webhook_cache. The function’s own log line only has the count, format and HTTP status, never the webhook URL. Memory Size: 3008 MB is the local emulator default, not the 128 MB configured in Terraform.

SeverityHIGHAccount / Region111122223333 / ap-southeast-1ResourceAwsEc2SecurityGroupOpen in console[HIGH] Security Hub: Sample: security groupallows 0.0.0.0/0 on port 22ILLUSTRATIONSlack: blocks · Teams: Adaptive Card
Layout illustration, redrawn from the exact JSON the receiver printed in step 6. Slack and Teams each render it in their own style.

Step 7: Connect a real Slack or Teams channel

What you are doing: get a real webhook URL and store it in Parameter Store without it ever touching a file.

Slack: create a Slack app, turn on Incoming Webhooks and add a webhook for the target channel. Slack gives you a URL of the form https://hooks.slack.com/services/.... POST JSON with text (plus blocks if you like) and Slack answers HTTP 200 with the body ok.

Microsoft Teams: Office 365 Connectors in Teams, including the connector-based Incoming Webhook, were retired by Microsoft in May 2026. The replacement is the Workflows app (Power Automate): in the channel, pick the “Send webhook alerts to a channel” template (trigger “When a Teams webhook request is received”) and Workflows gives you a webhook URL. That URL accepts the Adaptive Card the function already sends.

Store the URL, for example with Terraform (bump value_wo_version to 2 first):

Terminal window
read -rs TF_VAR_webhook_url && export TF_VAR_webhook_url # paste the URL, nothing is echoed
terraform apply -var chat_format=teams

Or write it directly with the AWS CLI, if Terraform does not manage the parameter:

Terminal window
aws ssm put-parameter --name /l05/chat/webhook-url --type SecureString --overwrite \
--value "https://example.invalid/replace-with-your-webhook"
Command Meaning Why
read -rs Reads the value from the keyboard without echoing it The URL does not end up in your shell history (~/.bash_history).
value_wo_version to 2 Tells Terraform there is a new value Terraform does not store the old value, so it cannot tell you changed it.
--overwrite Replaces the existing parameter Without it, put-parameter fails because the parameter already exists.

How to read the result (on a real channel; the lab does not run this part): once the URL is stored, wait for a new HIGH or CRITICAL finding, or create one GuardDuty sample finding with aws guardduty create-sample-findings --detector-id <id> --finding-types <type>, picking a High type from the GuardDuty finding types table. Avoid the console button Generate sample findings: it creates one finding for every type, so the channel gets a burst of messages at once. Sample findings have titles starting with [SAMPLE]. A message in the channel starting with [HIGH] ... or [CRITICAL] ... means the whole chain works. No message? Walk the 6 hops of the lab model backwards, starting with the log group /aws/lambda/l05-security-alert-chat. A "sent": 1 line with an http_status other than 200 points at the webhook; no log line at all means the rule never invoked the function.

Do you need your own Lambda? Amazon Q Developer in chat applications

AWS has a managed way to send notifications to chat: Amazon Q Developer in chat applications (formerly AWS Chatbot). It supports Amazon Chime, Microsoft Teams and Slack and receives notifications through SNS topics: an EventBridge rule targets an SNS topic and Q Developer posts to the channel. Sending notifications and running CLI commands has no additional charge.

Choose When
Amazon Q Developer in chat applications You want little code, accept the AWS message format (customisable with custom notifications), and your Slack/Teams admins allow the AWS app.
EventBridge + Lambda, as in this guide You need your own format, extra filtering in code, grouping or de-duplication, a destination that is not supported, or your organisation does not allow third-party apps in Slack/Teams.

Avoiding alert fatigue

  • Only HIGH and CRITICAL go to chat. Review the rest on a schedule in the console or in a weekly report.
  • Pick one path for GuardDuty. When both GuardDuty and Security Hub CSPM are enabled, the integration turns on automatically and GuardDuty sends its findings to Security Hub CSPM. Keep both rules and one detection may alert twice. If you use Security Hub CSPM, keep only the Security Hub rule.
  • NEW does not remove every repeat. Security Hub CSPM sends an event for every update; a finding that is still NEW and gets updated produces another event, and a finding reset to NEW (for example from ARCHIVED back to ACTIVE) alerts again. For strict de-duplication, store the IDs of findings you already alerted on (for example in DynamoDB with a 24-hour TTL) and skip known ones.
  • Change the status after alerting. Once handled, set Workflow.Status to NOTIFIED or RESOLVED and the finding no longer passes the pattern.
  • Group messages. The function already groups several findings into one message (+N more). For large bursts, consider a small reserved concurrency so you stay under the webhook rate limits.

Applying this on real AWS

  • Remove the fake keys, the three skip_* lines and the endpoints block from the provider. Use a separate test account and set up AWS Budgets first.
  • Regions and accounts: an EventBridge rule only sees events from its own Region. In the Security Hub CSPM aggregation Region, the event feed includes findings from linked Regions; in an administrator account, it includes member account findings. Put the rule there to catch everything; without aggregation you need a rule per Region.
  • Run aws events test-event-pattern with the sample event files before creating the rules.
  • Test the real path too: GuardDuty can generate sample findings, so you can test without a real incident.
  • Add a CloudWatch alarm on function errors (the Errors metric). An alerting function that breaks fails silently.
  • Cost: GuardDuty has a 30-day free trial per Region; Security Hub CSPM has a 30-day free trial, then charges for security checks, findings ingested (10,000 findings per account per Region per month are free) and rule evaluations. Lambda’s free tier includes 1 million requests per month. Standard SSM parameters have no additional charge.

Common errors

Symptom Cause Fix
aws events test-event-pattern on Moto prints nothing, exit 0 Moto does not implement TestEventPattern Test through PutEvents → SQS (step 3) or run the command in a real account
The Security Hub rule on Moto does not catch the HIGH event Moto cannot match a pattern inside the detail.findings[] array of objects A Moto limitation; check with Event Ruler or test-event-pattern on AWS
NoRegionError: You must specify a region. when running the Lambda image locally No Region for boto3 Add -e AWS_DEFAULT_REGION=...
AccessDeniedException on GetParameter on AWS The role lacks ssm:GetParameter on that exact parameter ARN, or kms:Decrypt Compare with part 2 of the Terraform; with a customer managed key the key policy must also allow the role
Findings appear in the console but no message arrives Rule in another Region, wrong detail-type (the new Security Hub uses Findings Imported V2), or missing aws_lambda_permission Check the Region, the pattern and the rule’s FailedInvocations metric
Slack returns invalid_payload or no_text JSON not in Slack’s shape, or text missing Compare with slack_payload
Slack returns HTTP 429 Too Many Requests Posting too fast to one webhook Group messages, lower concurrency
Teams shows nothing, you are still on an old Office 365 Connector webhook Office 365 Connectors are retired Create a new webhook with Workflows (step 7)

Clean up

Terminal window
docker rm -f l05-lambda l05-receiver
terraform destroy -auto-approve
awsl events remove-targets --rule l05-gd-high --event-bus-name l05-lab --ids matched
awsl events delete-rule --name l05-gd-high --event-bus-name l05-lab
awsl events delete-event-bus --name l05-lab
awsl sqs delete-queue --queue-url "$Q"

FAQ

Why not send every finding to chat, just to be safe? A noisy channel gets muted, and the real alert drowns with the noise. Chat is for things to act on now; the rest belongs in the console.

Security Hub CSPM already collects GuardDuty findings. Do I need a separate GuardDuty rule? Not if Security Hub CSPM is enabled. Keep one path to avoid duplicate alerts. A dedicated GuardDuty rule makes sense when you only run GuardDuty.

What changes for the new Security Hub (OCSF)? Change the detail-type to Findings Imported V2 and rewrite the pattern and function for OCSF field names. EventBridge, Lambda, SSM and Terraform stay the same.

Should I use Secrets Manager instead of Parameter Store? You can. Secrets Manager adds automatic rotation but charges per secret. For a webhook URL that rarely changes, a SecureString is enough.

Does my old Teams webhook still work? No. According to Microsoft, Office 365 Connectors in Teams, including connector-based Incoming Webhooks, stopped working in May 2026. Recreate it with Workflows.

References

Cao Le Nam Trung

Cao Le Nam Trung

Cloud & Network Engineer · TrungCLN

Designs and runs AWS infrastructure, hybrid networking (VPN, BGP) and cloud security. Every guide on this site is built and run for real before it is written.

LinkedIn YouTube Facebook

Related guides