Exercise 1: New Member Onboarding
Objective
When a new user is added to your Cloudflare account, automatically trigger a Terraform Cloud run and send a welcome message to Telegram.
This exercise teaches you how to build event-driven automation that responds to account changes, demonstrating real-world operational workflows that reduce manual overhead and ensure consistent onboarding processes.
What You'll Learn
- Cron-based Polling: Monitor Cloudflare audit logs for new member events
- State Management: Track processed events using KV storage
- API Integration: Connect to Terraform Cloud and Telegram APIs
- Production Patterns: Build resilient automation with error handling
Architecture Overview
Cloudflare Account Changes → Audit Log → Worker (Cron) → State Check → Actions
↓
KV Storage
↓
[Terraform Cloud API + Telegram Bot]
- Trigger: Cron-based polling of Account Audit Log every 5 minutes
- Actions: Terraform Cloud API call + Telegram notification
- State Management: KV store to track last processed event timestamp
Prerequisites
Before starting this exercise, ensure you have:
- Cloudflare account with API access
- Telegram bot token and chat/channel ID
- Terraform Cloud account and API token
- Basic understanding of Workers and KV storage
Instructions
1. Project Setup
Create a new Worker project using the latest C3 CLI:
npm create cloudflare@latest onboarding-worker
# Select "Hello World" Worker
# Choose TypeScript
# Select "Yes" to deploy
cd onboarding-worker
2. Configure Secrets
Add the required API tokens and credentials:
npx wrangler secret put TELEGRAM_WEBHOOK_URL
npx wrangler secret put TFC_API_TOKEN
npx wrangler secret put CLOUDFLARE_API_TOKEN
npx wrangler secret put CLOUDFLARE_ACCOUNT_ID
3. Create KV Namespace
Set up state storage to track processed events:
npx wrangler kv namespace create STATE_STORE
4. Configure Wrangler
Update your wrangler.jsonc with cron triggers and KV binding:
{
"name": "onboarding-worker",
"main": "src/index.ts",
"compatibility_date": "2024-12-02",
"vars": {
"TFC_ORGANIZATION": "your-tfc-org",
"TFC_WORKSPACE_NAME": "your-tfc-workspace"
},
"triggers": {
"crons": ["*/5 * * * *"]
},
"kv_namespaces": [
{
"binding": "STATE_STORE",
"id": "your_kv_namespace_id"
}
]
}
5. Implementation Challenge
Your task is to implement a Worker that:
- Polls the Cloudflare audit log API for new member addition events
- Maintains state using KV to avoid processing duplicate events
- Triggers a Terraform Cloud workspace run when new members are detected
- Sends a welcome message via Telegram webhook
- Handles errors gracefully and logs important events
Key Requirements:
- Use the
/audit_logsendpoint with proper filtering - Store the last check timestamp in KV storage
- Extract user email from audit log entries
- Make authenticated API calls to Terraform Cloud
- Send formatted notifications to Telegram
💡 Hint: API Endpoints
Cloudflare Audit Logs:
GET https://api.cloudflare.com/client/v4/accounts/{account_id}/audit_logs?action.type=add&since={timestamp}
Terraform Cloud Runs:
POST https://app.terraform.io/api/v2/runs
Content-Type: application/vnd.api+json
Authorization: Bearer {token}
Telegram Webhook:
POST {webhook_url}
Content-Type: application/json
Body: {"text": "Welcome message"}
🔧 Hint: Implementation Structure
Your Worker should have these key functions:
scheduled()handler - Main cron entry pointfetchAuditLogs()- Get recent audit log entriestriggerTerraformRun()- Start TFC workspace runsendTelegramNotification()- Send welcome message- Error handling and state management throughout
Testing Your Solution
- Local Development: Use
npx wrangler devand trigger manually - Deploy:
npx wrangler deployand monitor logs - Validation: Add a test user to verify the full workflow
- Monitoring: Check KV storage and external service logs
Success Criteria
Your implementation should:
- ✅ Successfully poll audit logs without errors
- ✅ Detect new member additions accurately
- ✅ Trigger Terraform Cloud runs with proper payloads
- ✅ Send formatted Telegram notifications
- ✅ Maintain state to prevent duplicate processing
- ✅ Handle API failures gracefully with retries
Solution
🔒 Complete Implementation
This content is password-protected. Enter the password to view the content.
Next Steps
Once you've completed this exercise, you've built a production-ready automation that demonstrates:
- Event-driven architecture patterns
- State management with distributed storage
- Integration with multiple external APIs
- Error handling and observability
This pattern can be extended for other account events like user removals, permission changes, or security incidents!