Fun Facts Generator
fahrican/fun-facts-generator
API serverless AWS com fatos gerados por IA usando Terraform
Ver no GitHubAplicação serverless AWS que gera fatos sobre computação em nuvem enriquecidos com IA via API REST. Utiliza Lambda, DynamoDB, API Gateway e AWS Bedrock (Claude 3.5 Sonnet) orquestrados por Terraform para infraestrutura como código.
Instalação
npx convez-ai fahrican/fun-facts-generator1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.
Métricas
Casos de uso
- Demonstrar arquitetura serverless completa na AWS
- Aprender Infrastructure as Code com Terraform
- Integrar Claude 3.5 Sonnet via AWS Bedrock em aplicações cloud
Veredito

Projeto prático e bem estruturado para aprender serverless + IaC na AWS, mas exige conhecimento prévio de AWS, Terraform e Python. Valor educacional alto; código limpo e documentação clara facilitam reprodução em produção.
README
A tradução para o português deste README ainda está na fila.
Fun Facts Generator
A serverless AWS application that delivers AI-enhanced cloud computing facts through a REST API. Built with Terraform, S3, AWS Lambda, DynamoDB, API Gateway, and AWS Bedrock (Claude 3.5 Sonnet).
🚀 Features
- Serverless Architecture: Fully managed AWS Lambda function
- AI-Powered: Uses AWS Bedrock's Claude 3.5 Sonnet to transform plain facts into witty, engaging content
- DynamoDB Storage: Stores cloud computing facts with scalable NoSQL database
- REST API: Simple HTTP GET endpoint via API Gateway
- Remote State Management: Terraform state stored in S3 with DynamoDB locking
- Infrastructure as Code: Complete Terraform configuration for reproducible deployments
- CORS Enabled: Ready for frontend integration
📋 Architecture
API Gateway → Lambda Function → DynamoDB (facts storage)
↓
AWS Bedrock (Claude 3.5 Sonnet)
Terraform State: S3 Bucket + DynamoDB Lock Table
🛠️ Prerequisites
- AWS Account with appropriate permissions
- Terraform ~> 1.7
- AWS CLI configured
- Python 3.11+
- AWS Bedrock access enabled for Anthropic Claude 3.5 Sonnet
📦 Project Structure
.
├── iac/ # Infrastructure as Code (Terraform)
│ ├── .terraform/ # Terraform cache directory
│ ├── .terraform.lock.hcl # Terraform dependency lock file
│ ├── amplify.tf # AWS Amplify configuration
│ ├── api-gateway.tf # API Gateway configuration
│ ├── backend.tf # Terraform S3 backend configuration
│ ├── bootstrap/ # Bootstrap resources (managed separately)
│ │ └── bootstrap.tf # S3 bucket & DynamoDB table for state
│ ├── iam.tf # IAM roles and policies
│ ├── main.tf # Main Terraform configuration
│ ├── outputs.tf # Terraform output definitions
│ ├── providers.tf # Provider configurations
│ ├── storage.tf # Storage resources (DynamoDB)
│ ├── terraform.tfvars # Variable definitions
│ └── variables.tf # Variable declarations
│
├── src/ # Source code
│ ├── backend/ # Backend services
│ │ ├── facts.py # Lambda function code
│ │ ├── lambda_function.zip # Lambda deployment package
│ │ ├── populate_dynamodb.py # Script to populate initial facts
│ │ └── requirements.txt # Python dependencies
│ │
│ └── frontend/ # Frontend application
│ └── index.html # Frontend web interface
│
├── .gitignore # Git ignore file
├── .terraform/ # Terraform working directory
├── .venv/ # Python virtual environment
├── .idea/ # IDE specific files
├── LICENSE # MIT License
└── README.md # Project documentation
🚀 Deployment
1. Set Up AWS Bedrock Access
Before deploying, enable Bedrock access:
- Go to AWS Bedrock Console in
us-east-1 - Navigate to Model catalog
- Find Claude 3.5 Sonnet and open it in the Playground
- Fill out the Anthropic use case details form (first-time users only)
- Wait up to 15 minutes for approval
2. Create S3 Backend (First-Time Setup Only)
Important: The S3 bucket and DynamoDB table for Terraform state must be created before initializing Terraform.
# Navigate to infrastructure directory
cd iac
# Create the S3 bucket for state storage
aws s3api create-bucket \
--bucket cloud-facts-generator-tfstate \
--region eu-central-1 \
--create-bucket-configuration LocationConstraint=eu-central-1
# Enable versioning (recommended for state file history)
aws s3api put-bucket-versioning \
--bucket cloud-facts-generator-tfstate \
--versioning-configuration Status=Enabled
# Enable encryption
aws s3api put-bucket-encryption \
--bucket cloud-facts-generator-tfstate \
--server-side-encryption-configuration '{
"Rules": [{
"ApplyServerSideEncryptionByDefault": {
"SSEAlgorithm": "AES256"
}
}]
}'
# Create DynamoDB table for state locking
aws dynamodb create-table \
--table-name terraform-lock \
--attribute-definitions AttributeName=LockID,AttributeType=S \
--key-schema AttributeName=LockID,KeyType=HASH \
--billing-mode PAY_PER_REQUEST \
--region eu-central-1
Alternative: Use the bootstrap/bootstrap.tf file (see Bootstrap section below)
3. Create Lambda Deployment Package
cd src/backend/
zip lambda_function.zip facts.py
4. Initialize Terraform
Navigate to the iac/ folder:
cd ../../iac
terraform init
5. Deploy Infrastructure
terraform plan
terraform apply
After deployment, Terraform will output your API endpoint URL.
6. Install Python Dependencies (for populate script)
Navigate back to the src/backend/ folder:
cd ../src/backend
pip install -r requirements.txt
Note: The Lambda function doesn't need this as boto3 is included in the AWS Lambda Python runtime.
7. Populate DynamoDB with Facts
python3 populate_dynamodb.py
This script inserts 15 cloud computing facts into your DynamoDB table.
🏗️ Bootstrap Resources (Advanced)
The bootstrap/ directory contains Terraform configuration for creating the S3 bucket and DynamoDB table used for
remote state storage. These resources are managed separately from your main infrastructure to avoid circular
dependencies.
Using bootstrap.tf
If you prefer to use Terraform to create the backend resources:
- Navigate to bootstrap directory:
cd iac/bootstrap
- Initialize and apply:
terraform init
terraform apply
- Return to main infrastructure:
cd ..
terraform init
Note: Bootstrap resources should not be managed by the same Terraform state that uses them as a backend.
🔧 State Management
Viewing Current State
# List all resources in state
terraform state list
# Show details of a specific resource
terraform state show aws_lambda_function.general_cloud_facts
Removing Resources from State
If you need to stop managing a resource with Terraform without deleting it from AWS:
terraform state rm <resource_address>
Example: Remove bootstrap resources from state (after moving them to separate config):
terraform state rm aws_s3_bucket.terraform_state
terraform state rm aws_s3_bucket_versioning.terraform_state
terraform state rm aws_s3_bucket_server_side_encryption_configuration.terraform_state
terraform state rm aws_dynamodb_table.terraform_lock
Migrating State
To migrate from local state to S3 backend:
terraform init -migrate-state
To reconfigure backend settings:
terraform init -reconfigure
🧪 Testing
Test the API endpoint:
curl https://your-api-gateway-url.execute-api.eu-central-1.amazonaws.com/cloudfact
Expected response:
{
"fact": "AWS S3 has been around since 2006 — older than the first iPhone and still storing your selfies like a champ! 📸"
}
📝 API Documentation
GET /cloudfact
Returns a random cloud computing fact enhanced by AI.
Response Format:
{
"fact": "string"
}
Status Codes:
200 OK: Successfully retrieved fact500 Internal Server Error: No facts available
CORS Headers:
Access-Control-Allow-Origin: *Access-Control-Allow-Methods: GET, OPTIONSAccess-Control-Allow-Headers: Content-Type
🔧 Configuration
AWS Resources Created
- Lambda Function:
GeneralCloudFacts(Python 3.13 runtime) - DynamoDB Table:
CloudFacts(Pay-per-request billing) - API Gateway:
CloudFactsAPI(HTTP API) - IAM Role:
GeneralCloudFacts_lambda_rolewith policies for:- CloudWatch Logs
- DynamoDB read access
- Bedrock model invocation
- CloudWatch Log Group: 7-day retention
Backend Resources (Managed Separately)
- S3 Bucket:
cloud-facts-generator-tfstate(Terraform state storage) - DynamoDB Table:
terraform-lock(State locking)
Environment Variables
The Lambda function uses the following environment variables:
ENV: Deployment environment (default:production)DYNAMODB_TABLE: DynamoDB table name (set automatically by Terraform)
AWS Regions
- Lambda & DynamoDB:
eu-central-1 - Bedrock (Claude):
us-east-1
💡 How It Works
- Request: User hits the
/cloudfactendpoint - Fetch: Lambda scans DynamoDB for all facts
- Select: Random fact is chosen
- Transform: AWS Bedrock's Claude 3.5 Sonnet makes the fact witty and engaging
- Fallback: If Bedrock fails, original fact is returned
- Response: JSON response with the fact
🔒 Security
- IAM roles follow principle of least privilege
- API Gateway uses HTTPS by default
- CloudWatch logging enabled for monitoring
- DynamoDB and Lambda in private AWS network
- Terraform state encrypted at rest in S3
- State locking prevents concurrent modifications
💰 Cost Considerations
- Lambda: Free tier includes 1M requests/month
- DynamoDB: Pay-per-request pricing (very low cost for small datasets)
- API Gateway: $1.00 per million requests after free tier
- Bedrock: Pay-per-use (~$0.003 per 1K input tokens, ~$0.015 per 1K output tokens)
- CloudWatch Logs: First 5GB/month free
- S3 (State Storage): Minimal cost (~$0.023/GB/month)
🧹 Cleanup
To destroy all resources:
terraform destroy
Note: This will permanently delete your DynamoDB table and all facts, but will NOT delete the S3 state bucket or DynamoDB lock table (managed separately).
To also remove backend resources:
# Delete DynamoDB lock table
aws dynamodb delete-table --table-name terraform-lock --region eu-central-1
# Empty and delete S3 bucket
aws s3 rm s3://cloud-facts-generator-tfstate --recursive
aws s3 rb s3://cloud-facts-generator-tfstate
🐛 Troubleshooting
Facts aren't being transformed by AI
Check CloudWatch logs:
aws logs tail /aws/lambda/GeneralCloudFacts --follow --region eu-central-1
Common issues:
- Bedrock use case form not submitted
- IAM permissions not applied (run
terraform applyagain) - Model not available in region (ensure using
us-east-1for Bedrock)
API returns "No facts found"
Run the population script:
python3 populate_dynamodb.py
Terraform State Lock Errors
If Terraform crashes and leaves a lock:
terraform force-unlock <LOCK_ID>
Backend Initialization Errors
If you get "S3 bucket does not exist" or "DynamoDB table not found":
- Ensure you created the backend resources (see Step 2)
- Verify bucket name and table name in
backend.tfmatch what you created - Check you're in the correct AWS region
Terraform errors
Ensure AWS credentials are configured:
aws configure
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- AWS for providing serverless infrastructure
- Anthropic for Claude 3.5 Sonnet
- Terraform for infrastructure as code
🚀 AWS Amplify Quick Start
Your Amplify configuration is ready! Follow these steps to deploy your frontend.
Step 1: Create GitHub Personal Access Token
- Go to https://github.com/settings/tokens/new
- Note:
Amplify Access for fun-facts-generator - Expiration:
90 days(or your preference) - Select scopes:
- ✅ repo (Full control of private repositories)
- Click Generate token
- Copy the token (you won't see it again!)
Step 2: Configure Terraform with Your Token
Create terraform.tfvars file:
cp terraform.tfvars.example terraform.tfvars
Edit terraform.tfvars and paste your GitHub token:
github_access_token = "ghp_YOUR_ACTUAL_TOKEN_HERE"
Important: This file is already in .gitignore - never commit it!
Step 3: Deploy to AWS Amplify
# Initialize Terraform (if not done)
terraform init
# Preview changes
terraform plan
# Deploy everything
terraform apply
Type yes when prompted.
Step 4: Get Your Live URL
After deployment completes:
terraform output amplify_app_url
You'll get a URL like: https://main.d1a2b3c4d5e6f7.amplifyapp.com
Step 5: Push Changes to Auto-Deploy
From now on, every time you push to GitHub:
git add .
git commit -m "Update frontend"
git push
Amplify will automatically build and deploy your changes in ~1-2 minutes!
📊 Monitoring
View your deployments:
- AWS Console: https://console.aws.amazon.com/amplify/
- Build logs show real-time deployment progress
- Each Git commit triggers a new build
🔧 Troubleshooting
"Repository not found" error
- Verify your GitHub token is correct in
terraform.tfvars - Check token has
repopermissions - Ensure repository URL is correct:
https://github.com/fahrican/fun-facts-generator
Build fails
- Check build logs in Amplify Console
- Verify
index.htmlis in the repository root - Build spec in
amplify.tfis configured for static HTML
"Access token expired"
- Generate a new GitHub token
- Update
terraform.tfvars - Run
terraform applyagain
🧹 Cleanup
To remove Amplify hosting (keeps Lambda/API):
terraform destroy -target=aws_amplify_app.fun_facts_frontend
terraform destroy -target=aws_amplify_branch.main
To remove everything:
terraform destroy
Your Site: https://main.d2ytneb90go8i0.amplifyapp.com/index.html
AWS Region: eu-central-1