Imagine this: Your EC2 instance's CPU is suddenly spiking, but you miss the CloudWatch email alert buried under dozens of other notifications. What if, instead, your phone rings with a voice message warning you of the spike?
Welcome to a hands-on guide where we'll combine AWS Lambda, CloudWatch, and Twilio to send real-time phone call alerts whenever your EC2 instance breaches a certain threshold - no more missed alerts.
🔧 What You'll Build
By the end of this tutorial, you'll have a serverless system that:
- Detects high CPU usage using CloudWatch
- Sends an SNS notification
- Triggers an AWS Lambda function
- Uses Twilio to make a real phone call with a custom alert message
Let's jump right in!
📦 Step 1: Create the Lambda Function
Head over to the AWS Lambda Console and follow these steps:
- Click "Create function."
- Choose "Author from scratch."
- Name it something like CallOnHighCPU
- Runtime: Python 3.9 (or higher)
- Click "Create function."
📞 Step 2: Package Twilio with Your Lambda Code
AWS Lambda doesn't include third-party packages by default. Let's package the Twilio SDK:
👉 On your local machine, run:
mkdir lambda_twilio && cd lambda_twilio
pip install twilio -t .
zip -r9 ../lambda_function.zip .
Now, add your Lambda function code.
Create a file called lambda_function.py inside lambda_twilio/:
import json
import os
from twilio.rest import Client
TWILIO_ACCOUNT_SID = os.environ['TWILIO_ACCOUNT_SID']
TWILIO_AUTH_TOKEN = os.environ['TWILIO_AUTH_TOKEN']
TWILIO_PHONE_NUMBER = os.environ['TWILIO_PHONE_NUMBER']
YOUR_PHONE_NUMBER = os.environ['YOUR_PHONE_NUMBER']
def lambda_handler(event, context):
try:
sns_message = event['Records'][0]['Sns']['Message']
alarm_name = json.loads(sns_message).get("AlarmName", "Unknown Alert")
metric_name = json.loads(sns_message).get("Trigger", {}).get("MetricName", "Unknown Metric")
alert_message = f"Alert! {alarm_name} triggered due to high {metric_name} usage. Please check your server. Thanks!!"
client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
twiml_response = f"""
{alert_message}
"""
call = client.calls.create(
to=YOUR_PHONE_NUMBER,
from_=TWILIO_PHONE_NUMBER,
twiml=twiml_response
)
print(f"Call initiated with SID: {call.sid}")
return {
'statusCode': 200,
'body': json.dumps(f'Call initiated for {alarm_name}')
}
except Exception as e:
print(f"Error: {str(e)}")
return {
'statusCode': 500,
'body': json.dumps(f"Error: {str(e)}")
}
Then, add it to your ZIP:
zip -g ../lambda_function.zip lambda_function.py
This zip now contains:
- Your Lambda code
- The Twilio SDK
☁️ Step 3: Upload to Lambda
Back in the AWS Lambda Console:
- Open your CallOnHighCPU function
- Go to Code → Choose "Upload from" → "ZIP file"
- Upload your lambda_function.zip
- Click Deploy
🔐 Step 4: Set Environment Variables
Still in the Lambda console:
- Go to Configuration → Environment Variables → Edit
- Add:
TWILIO_ACCOUNT_SID =
TWILIO_AUTH_TOKEN =
TWILIO_PHONE_NUMBER = +1234567890
YOUR_PHONE_NUMBER = +9876543210
Save changes.
✨ If you don't have a Twilio account, create one. You'll get $15 free credit for testing.
🧪 Step 5: Test the Lambda Function
Click "Test" and create a new event:
Test Event JSON (SNS format):
{
"Records": [
{
"Sns": {
"Message": "{\"AlarmName\":\"HighCPUUsage\",\"Trigger\":{\"MetricName\":\"CPUUtilization\"}}"
}
}
]
}
Run the test. Your phone should ring with the alert message. Magic!
📣 Step 6: Connect Lambda to SNS
Now, let's wire up SNS to trigger your function.
6.1: Create an SNS Topic
- Go to SNS Console
- Click Create Topic
- Type: Standard
- Name:HighCPUAlert
- Click Create Topic
6.2: Create a Subscription
- Open your HighCPUAlert topic
- Click Create Subscription
- Protocol: Lambda
- Endpoint: Select your CallOnHighCPU Lambda
- Click Create Subscription
📊 Step 7: Attach SNS to a CloudWatch Alarm
- Go to CloudWatch → Alarms → Create Alarm
- Choose EC2 → Per-Instance Metrics
- Select CPUUtilization for your instance
- Conditions:
- Greater than 80%
- For 2 periods of 5 minutes
- In actions, choose SNS topic → HighCPUAlert
- Click Create Alarm
🔥 Bonus: Trigger the Alarm with a CPU Spike
On your EC2 instance, simulate CPU load:
sudo apt install stress
stress --cpu 2 --timeout 120s
Within minutes, CloudWatch will detect the spike, SNS will publish a message, Lambda will be triggered, and… your phone will ring.
🎉 You're Done!
You've successfully built a voice-based monitoring system using AWS Lambda, CloudWatch, SNS, and Twilio.
This solution is
- Real-time
- Reliable
- Easy to extend
Need to alert a team? Add multiple Twilio calls. Want Slack integration instead? Swap Twilio with a Slack webhook.
🙌 Final Thoughts
Email alerts are great, but voice alerts are immediate, hard to ignore, and potentially life-saving in production environments.
With just a few lines of code and some AWS configuration, you now have an automated voice call alert system that keeps your infrastructure healthy and your response time sharp.