Imagine getting real-time NBA game updates delivered straight to your phone or email without lifting a finger. Now, imagine provisioning that entire system in just 15 seconds! 🤯
In this blog, we’ll walk through how to build an NBA Game Day Notification System using AWS serverless technologies and Infrastructure as Code (IaC) with Terraform. This system fetches live NBA scores and sends updates via SMS and email to subscribed users.
Previously, setting up this solution manually took several minutes. But with Terraform, we can automate and replicate the deployment effortlessly—making it scalable, repeatable, and secure.
Here’s what we’ll cover:
âś… How the system works
âś… Why Infrastructure as Code (IaC) is a game-changer
âś… Step-by-step deployment using AWS & Terraform
âś… How to test and optimize your notifications
Let’s dive in! 🚀
Project Overview
The NBA Game Day Notification System is designed to:
- Fetch real-time NBA scores from an external API.
- Process the data and send notifications via SMS and email to subscribed users.
Here’s the tech stack we’ll use:
🔹 AWS Lambda – Fetches live NBA scores from an API.
🔹 Amazon SNS – Sends notifications via SMS/Email.
🔹 Amazon EventBridge – Triggers updates at scheduled intervals.
🔹 Terraform (IaC) – Automates deployment of the entire infrastructure.
🔹 Python & External APIs – Handles data processing and API integration.
System Architecture
Here’s how the system works:
- EventBridge Scheduler triggers an AWS Lambda function at scheduled intervals (e.g., every 2 hours).
- The Lambda function fetches live NBA game data from an external API (SportsData.io).
- The function processes the scores and sends notifications via Amazon SNS.
- Users receive real-time game updates via SMS or Email.
Code Breakdown
Terraform Configuration (game_day_notifications.tf)
The Terraform file provisions all the necessary AWS resources:
- SNS Topic – For sending notifications.
- IAM Role and Policies – Grants Lambda access to SNS, SSM, and CloudWatch.
- Lambda Function – Fetches NBA scores and processes data.
- EventBridge Rule – Triggers the Lambda function every 2 hours.
Here’s a snippet of the Terraform configuration:
provider "aws" {
region = "us-east-1" # Change as needed
}
# SNS Topic
resource "aws_sns_topic" "nba_game_alerts" {
name = "nba_game_alerts"
}
# IAM Role for Lambda
resource "aws_iam_role" "lambda_role" {
name = "nba_lambda_role"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}
# IAM Policy for Lambda to publish to SNS
resource "aws_iam_policy" "sns_publish_policy" {
name = "sns_publish_policy"
description = "Policy to allow Lambda to publish to SNS"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "sns:Publish",
"Resource": "${aws_sns_topic.nba_game_alerts.arn}"
}
]
}
EOF
}
# Attach IAM Policy for Lambda to publish to SNS to IAM Role
resource "aws_iam_role_policy_attachment" "attach_sns_publish" {
role = aws_iam_role.lambda_role.name
policy_arn = aws_iam_policy.sns_publish_policy.arn
}
Python Script (nba_notifications.py)
The Python script handles:
- Fetching the API key securely from AWS SSM.
- Getting live NBA scores from SportsData.io.
- Processing and formatting the game data.
- Publishing game updates to SNS for notifications.
Here’s a snippet of the Python script:
import os
import json
import urllib.request
import boto3
from datetime import datetime, timedelta, timezone
def format_game_data(game):
status = game.get("Status", "Unknown")
away_team = game.get("AwayTeam", "Unknown")
home_team = game.get("HomeTeam", "Unknown")
final_score = f"{game.get('AwayTeamScore', 'N/A')}-{game.get('HomeTeamScore', 'N/A')}"
start_time = game.get("DateTime", "Unknown")
channel = game.get("Channel", "Unknown")
# Format quarters
quarters = game.get("Quarters", [])
quarter_scores = ', '.join([f"Q{q['Number']}: {q.get('AwayScore', 'N/A')}-{q.get('HomeScore', 'N/A')}" for q in quarters])
if status == "Final":
return (
f"Game Status: {status}\n"
f"{away_team} vs {home_team}\n"
f"Final Score: {final_score}\n"
f"Start Time: {start_time}\n"
f"Channel: {channel}\n"
f"Quarter Scores: {quarter_scores}\n"
)
elif status == "InProgress":
last_play = game.get("LastPlay", "N/A")
return (
f"Game Status: {status}\n"
f"{away_team} vs {home_team}\n"
f"Current Score: {final_score}\n"
f"Last Play: {last_play}\n"
f"Channel: {channel}\n"
)
elif status == "Scheduled":
return (
f"Game Status: {status}\n"
f"{away_team} vs {home_team}\n"
f"Start Time: {start_time}\n"
f"Channel: {channel}\n"
)
else:
return (
f"Game Status: {status}\n"
f"{away_team} vs {home_team}\n"
f"Details are unavailable at the moment.\n"
)
Step-by-Step Deployment
Step 1: Clone the Repository
First, clone the GitHub repository to your local machine:
git clone https://github.com/princemaxi/game-day-notifications_terraform
cd game-day-notifications
Step 2: Store API Key in AWS Systems Manager (SSM)
- To fetch NBA game data, we need an API key from SportsData.io.
- Once you have your API key, store it securely in AWS Systems Manager (SSM):
aws ssm put-parameter --name "nba-api-key" --value "<YOUR_API_KEY>" --type "SecureString"
This ensures your API key is stored securely instead of being hardcoded in your code. âś…
Step 3: Deploy Infrastructure with Terraform
- Initialize Terraform Run this command to initialize Terraform and download provider plugins:
terraform init
- Format Configuration Files To keep everything clean and readable, format Terraform files:
terraform fmt
- Validate Configuration Before applying, check for syntax errors:
terraform validate
- Plan Deployment Preview the changes Terraform will make:
terraform plan
- Apply Configuration Finally, deploy the infrastructure:
terraform apply -auto-approve
✨ Boom! In just 15 seconds, your entire system is up and running! 🚀
Step 4: Add SNS Subscriptions
After deployment, add users to the SNS Topic for notifications:
- Open AWS SNS in the AWS Console.
- Select the NBA Game Day SNS Topic.
- Click Create Subscription.
- Choose a protocol:
- Email: Enter a valid email.
- SMS: Enter a valid phone number (e.g., +1234567890).
- Click Create Subscription.
- For Email: Check your inbox and confirm the subscription.
Now, whenever there’s an NBA game, you’ll get real-time updates!
Step 5: Testing the System
Let’s test the solution:
- Go to AWS Lambda in the AWS Console.
- Select the nba_notifications Lambda function.
- Click Test and create a test event.
- Run the function and check CloudWatch logs.
- Verify SMS/Email notifications in your inbox or phone.
Success! You now have a fully automated, real-time NBA game notification system. 🎉
Step 6: Clean Up Resources with Terraform Destroy
Once you’re done testing or no longer need the system, you can clean up all the AWS resources created by Terraform with a single command:
terraform destroy -auto-approve
This command will:
- Delete the SNS Topic and its subscriptions.
- Remove the Lambda Function and its associated IAM roles and policies.
- Delete the EventBridge Rule and its permissions.
- Remove the SSM Parameter storing the API key.
Note: Be cautious when running this command, as it will permanently delete all resources managed by Terraform in this configuration.
Why Terraform & Infrastructure as Code (IaC)?
âś… Fast Deployment: What took minutes manually is now provisioned in 15 seconds.
âś… Scalability: Need more users? Just update the Terraform config.
âś… Security: IAM policies ensure least privilege access.
✅ Automation: No more manual configurations—Terraform handles it all.
Final Thoughts & Key Learnings
🚀 Building this project reinforced key DevOps principles:
✔️ IaC is a game-changer – Terraform made everything smooth and repeatable.
✔️ AWS Event-Driven Architecture enables real-time notifications.
✔️ Security matters – Storing secrets in AWS SSM keeps them safe.
✔️ Automation saves time – 15 seconds vs. several minutes of manual work!
🔥 Thank you for reading! If you found this helpful, share it with your network and follow for more DevOps insights! 🚀
💬 What are your thoughts on Terraform for infrastructure automation? Let’s discuss in the comments! ⬇️
Top comments (0)