Skip to content

fleetbase/cloudformation-template-docs

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Fleetbase AWS CloudFormation Template

License: AGPL v3 CloudFormation Version

A comprehensive, production-ready AWS CloudFormation template for deploying Fleetbase, the open-source logistics and fleet management platform. This template provides a complete infrastructure setup with enterprise-grade features including auto-scaling, high availability, SSL/TLS encryption, CDN distribution, and comprehensive monitoring.

πŸš€ Quick Start

Deploy Fleetbase to AWS in minutes with a single CloudFormation stack:

aws cloudformation create-stack \
  --stack-name fleetbase-production \
  --template-body file://template.yaml \
  --parameters ParameterKey=Project,ParameterValue=myfleet \
               ParameterKey=EnvironmentType,ParameterValue=production \
  --capabilities CAPABILITY_NAMED_IAM

πŸ“‹ Table of Contents

πŸ—οΈ Architecture Overview

This CloudFormation template deploys a highly available, scalable Fleetbase infrastructure on AWS using modern cloud-native services. The architecture follows AWS Well-Architected Framework principles and implements industry best practices for security, reliability, and performance.

Core Components

The deployment creates a complete microservices architecture with the following key components:

Frontend Layer:

  • Amazon CloudFront: Global content delivery network (CDN) that serves the Fleetbase console application with low latency worldwide
  • Amazon S3: Static website hosting for the compiled Ember.js frontend console application
  • SSL/TLS Certificates: Automated SSL certificate provisioning and management via AWS Certificate Manager

Application Layer:

  • Amazon ECS Fargate: Serverless container orchestration running multiple Fleetbase services:
    • API/Backend service (fleetbase/fleetbase-api:latest)
    • Event processing service for background jobs
    • Scheduled task service for cron jobs
    • SocketCluster service for real-time WebSocket communications
  • Application Load Balancer (ALB): Layer 7 load balancing with health checks and SSL termination
  • Auto Scaling: Automatic horizontal scaling based on CPU and memory utilization

Data Layer:

  • Amazon RDS MySQL: Managed relational database with automated backups, encryption at rest, and multi-AZ deployment options
  • Amazon ElastiCache Redis: In-memory caching and session storage for improved performance
  • Amazon S3: Object storage for file uploads, documents, and static assets

Integration Layer:

  • Amazon SQS: Message queuing service for reliable asynchronous job processing
  • AWS Systems Manager (SSM): Secure parameter storage and configuration management
  • AWS Secrets Manager: Encrypted storage for sensitive credentials and API keys

Networking:

  • Amazon VPC: Isolated virtual private cloud with public and private subnets across multiple Availability Zones
  • NAT Gateways: Secure outbound internet access for private subnet resources
  • Security Groups: Fine-grained network access control with least-privilege principles
  • Route53: DNS management and domain routing (when custom domains are configured)

High Availability Design

The template implements several high availability patterns:

  • Multi-AZ Deployment: Resources are distributed across multiple Availability Zones to ensure resilience against zone-level failures
  • Auto Scaling Groups: ECS services automatically scale based on demand and replace unhealthy instances
  • Database Redundancy: RDS supports automated backups and can be configured for Multi-AZ deployment
  • Load Balancer Health Checks: Continuous monitoring of application health with automatic traffic routing away from unhealthy instances
  • CloudFront Edge Locations: Global distribution ensures frontend availability even during regional outages

Security Architecture

Security is implemented at multiple layers:

  • Network Security: Private subnets isolate backend services from direct internet access
  • Encryption: Data encryption at rest (RDS, S3) and in transit (SSL/TLS everywhere)
  • IAM Roles: Least-privilege access controls with service-specific IAM roles
  • Secrets Management: Sensitive data stored in AWS Secrets Manager with automatic rotation capabilities
  • Security Groups: Network-level firewalls controlling traffic between services
  • VPC Flow Logs: Network traffic monitoring and analysis capabilities

Scalability Features

The architecture supports both vertical and horizontal scaling:

  • Container Scaling: ECS services can scale from 1 to 100+ instances based on demand
  • Database Scaling: RDS supports read replicas and can be upgraded to larger instance types
  • Cache Scaling: ElastiCache clusters can be scaled horizontally with additional nodes
  • CDN Scaling: CloudFront automatically handles traffic spikes with its global edge network
  • Storage Scaling: S3 provides virtually unlimited storage capacity with automatic scaling

✨ Features

πŸ”§ Infrastructure Features

Complete AWS Integration:

  • Fully managed AWS services with no server maintenance required
  • Automatic scaling and high availability across multiple Availability Zones
  • Enterprise-grade security with encryption at rest and in transit
  • Comprehensive monitoring and logging with CloudWatch integration
  • Cost-optimized resource allocation with Fargate serverless containers

Domain and SSL Management:

  • Automatic SSL certificate provisioning and renewal via AWS Certificate Manager
  • Custom domain support with Route53 DNS management
  • Flexible subdomain configuration (api.yourdomain.com, console.yourdomain.com)
  • CloudFront CDN with global edge locations for optimal performance
  • Automatic HTTP to HTTPS redirection for security compliance

Database and Caching:

  • Managed MySQL database with automated backups and point-in-time recovery
  • Redis caching layer for improved application performance
  • Database connection pooling and optimization
  • Automatic minor version updates and security patches
  • Configurable database instance types from micro to large scale

πŸš€ Application Features

Microservices Architecture:

  • Containerized services with independent scaling capabilities
  • API backend service handling REST endpoints and business logic
  • Real-time WebSocket communication via SocketCluster
  • Background job processing with SQS message queuing
  • Scheduled task execution for maintenance and reporting

Frontend Console:

  • Modern Ember.js single-page application
  • Responsive design optimized for desktop and mobile devices
  • Real-time updates via WebSocket connections
  • Comprehensive fleet management interface
  • Route optimization and mapping capabilities

File Storage and Processing:

  • S3 integration for document and image storage
  • Automatic file compression and optimization
  • Secure file upload and download capabilities
  • Image resizing and thumbnail generation
  • Document management with version control

πŸ›‘οΈ Security Features

Authentication and Authorization:

  • JWT-based authentication with secure token management
  • Role-based access control (RBAC) for different user types
  • API key management for third-party integrations
  • Session management with Redis-backed storage
  • Password encryption using industry-standard algorithms

Network Security:

  • Private subnet isolation for backend services
  • Security groups with least-privilege access rules
  • VPC endpoints for secure AWS service communication
  • Network ACLs for additional layer of protection
  • DDoS protection via CloudFront and AWS Shield

Data Protection:

  • Encryption at rest for all data storage services
  • SSL/TLS encryption for all data in transit
  • Secrets management via AWS Secrets Manager
  • Automated secret rotation capabilities
  • Audit logging for compliance requirements

πŸ“Š Monitoring and Operations

Comprehensive Logging:

  • Centralized logging via Amazon CloudWatch
  • Application logs from all microservices
  • Database query logging and performance metrics
  • Load balancer access logs and error tracking
  • Custom metrics and alerting capabilities

Performance Monitoring:

  • Real-time performance dashboards
  • Application performance monitoring (APM)
  • Database performance insights
  • Cache hit ratio monitoring
  • CDN performance analytics

Operational Excellence:

  • Automated deployment and rollback capabilities
  • Health checks and automatic recovery
  • Resource utilization monitoring
  • Cost optimization recommendations
  • Backup and disaster recovery procedures

πŸ”„ Integration Capabilities

API Ecosystem:

  • RESTful API with comprehensive documentation
  • WebSocket API for real-time communications
  • Webhook support for third-party integrations
  • Rate limiting and throttling protection
  • API versioning and backward compatibility

Third-Party Integrations:

  • Google Maps integration for routing and geocoding
  • SMS and email notification services
  • Payment gateway integration support
  • Fleet tracking device compatibility
  • ERP and CRM system integration capabilities

Data Export and Analytics:

  • CSV and Excel export functionality
  • Real-time analytics and reporting
  • Custom dashboard creation
  • Data visualization tools
  • Business intelligence integration support

πŸ“‹ Prerequisites

Before deploying this CloudFormation template, ensure you have the following prerequisites in place:

AWS Account Requirements

Account Setup:

  • Active AWS account with administrative privileges or appropriate IAM permissions
  • AWS CLI installed and configured with valid credentials
  • Sufficient service limits for the resources being created (ECS tasks, RDS instances, etc.)
  • Understanding of AWS billing and cost management practices

Required IAM Permissions: The deploying user or role must have permissions for the following AWS services:

  • Amazon ECS (Elastic Container Service)
  • Amazon RDS (Relational Database Service)
  • Amazon ElastiCache
  • Amazon S3
  • Amazon CloudFront
  • AWS Certificate Manager
  • Amazon Route53 (if using custom domains)
  • AWS Systems Manager
  • AWS Secrets Manager
  • Amazon SQS
  • AWS Lambda
  • Amazon VPC and associated networking services
  • AWS IAM (for creating service roles)
  • Amazon CloudWatch

Technical Prerequisites

Domain Configuration (Optional but Recommended): If you plan to use custom domains, you must have:

  • A registered domain name that you control
  • Access to modify DNS settings at your domain registrar
  • Understanding of DNS propagation and SSL certificate validation processes

Network Planning:

  • Familiarity with VPC networking concepts
  • Understanding of subnet CIDR blocks and IP address planning
  • Knowledge of security group configuration and network access control

Operational Knowledge:

  • Basic understanding of containerized applications and Docker
  • Familiarity with AWS CloudFormation template structure and parameters
  • Experience with monitoring and troubleshooting AWS services
  • Understanding of backup and disaster recovery procedures

Cost Considerations

Estimated Monthly Costs: The following provides rough cost estimates for different deployment scenarios (prices may vary by region):

Development Environment:

  • ECS Fargate tasks (minimal): $30-50/month
  • RDS db.t3.micro: $15-25/month
  • ElastiCache t3.micro: $15-20/month
  • CloudFront and S3: $5-10/month
  • Total: $65-105/month

Production Environment:

  • ECS Fargate tasks (scaled): $100-300/month
  • RDS db.t3.small or larger: $50-200/month
  • ElastiCache t3.small: $30-50/month
  • CloudFront, S3, and data transfer: $20-100/month
  • Total: $200-650/month

Additional costs may apply for:

  • Data transfer charges
  • CloudWatch logs retention
  • Route53 hosted zones ($0.50/month per zone)
  • SSL certificates (free with ACM)
  • SQS message processing

πŸš€ Deployment Options

This template supports multiple deployment scenarios to accommodate different use cases and environments.

Option 1: Quick Deployment (No Custom Domain)

Perfect for development, testing, or proof-of-concept deployments:

aws cloudformation create-stack \
  --stack-name fleetbase-dev \
  --template-body file://template.yaml \
  --parameters ParameterKey=Project,ParameterValue=fleetdev \
               ParameterKey=EnvironmentType,ParameterValue=development \
  --capabilities CAPABILITY_NAMED_IAM \
  --region us-east-1

This deployment will:

  • Use AWS-generated domain names (CloudFront and ALB DNS names)
  • Create a basic development environment with minimal resources
  • Provide immediate access via generated URLs
  • Use default security settings appropriate for development

Option 2: Production Deployment with Custom Domain

Recommended for production environments with professional domain setup:

aws cloudformation create-stack \
  --stack-name fleetbase-production \
  --template-body file://template.yaml \
  --parameters ParameterKey=Project,ParameterValue=mycompany \
               ParameterKey=EnvironmentType,ParameterValue=production \
               ParameterKey=RootDomainName,ParameterValue=mycompany.com \
               ParameterKey=ApiSubdomain,ParameterValue=api \
               ParameterKey=ConsoleSubdomain,ParameterValue=app \
               ParameterKey=SocketSubdomain,ParameterValue=socket \
               ParameterKey=DatabaseInstanceType,ParameterValue=db.t3.small \
  --capabilities CAPABILITY_NAMED_IAM \
  --region us-east-1

This deployment will:

  • Create SSL certificates for your custom domains
  • Set up Route53 DNS records automatically
  • Configure production-grade database and cache instances
  • Enable comprehensive monitoring and logging
  • Implement security best practices

Option 3: Existing Hosted Zone Deployment

For organizations with existing Route53 hosted zones:

aws cloudformation create-stack \
  --stack-name fleetbase-enterprise \
  --template-body file://template.yaml \
  --parameters ParameterKey=Project,ParameterValue=enterprise \
               ParameterKey=EnvironmentType,ParameterValue=production \
               ParameterKey=RootDomainName,ParameterValue=enterprise.com \
               ParameterKey=HostedZoneId,ParameterValue=Z1D633PJN98FT9 \
               ParameterKey=DatabaseInstanceType,ParameterValue=db.t3.medium \
               ParameterKey=CacheInstanceType,ParameterValue=cache.t3.small \
  --capabilities CAPABILITY_NAMED_IAM \
  --region us-east-1

Option 4: Multi-Environment Deployment

Deploy multiple environments (dev, staging, production) with environment-specific configurations:

# Development Environment
aws cloudformation create-stack \
  --stack-name fleetbase-dev \
  --template-body file://template.yaml \
  --parameters ParameterKey=Project,ParameterValue=myfleet \
               ParameterKey=EnvironmentType,ParameterValue=development \
               ParameterKey=DatabaseInstanceType,ParameterValue=db.t3.micro \
  --capabilities CAPABILITY_NAMED_IAM

# Staging Environment
aws cloudformation create-stack \
  --stack-name fleetbase-staging \
  --template-body file://template.yaml \
  --parameters ParameterKey=Project,ParameterValue=myfleet \
               ParameterKey=EnvironmentType,ParameterValue=staging \
               ParameterKey=RootDomainName,ParameterValue=mycompany.com \
               ParameterKey=ApiSubdomain,ParameterValue=staging-api \
               ParameterKey=ConsoleSubdomain,ParameterValue=staging-app \
  --capabilities CAPABILITY_NAMED_IAM

# Production Environment
aws cloudformation create-stack \
  --stack-name fleetbase-production \
  --template-body file://template.yaml \
  --parameters ParameterKey=Project,ParameterValue=myfleet \
               ParameterKey=EnvironmentType,ParameterValue=production \
               ParameterKey=RootDomainName,ParameterValue=mycompany.com \
               ParameterKey=DatabaseInstanceType,ParameterValue=db.t3.large \
  --capabilities CAPABILITY_NAMED_IAM

Deployment Validation

After deployment, validate your stack using these commands:

# Check stack status
aws cloudformation describe-stacks --stack-name fleetbase-production

# Verify resources are healthy
aws ecs describe-services --cluster fleetbase-production-cluster
aws rds describe-db-instances --db-instance-identifier fleetbase-production-database

# Test application endpoints
curl -I https://api.mycompany.com/health
curl -I https://app.mycompany.com

βš™οΈ Parameters

The CloudFormation template accepts the following parameters to customize your Fleetbase deployment:

Core Configuration Parameters

Parameter Type Default Description Required
Project String fleetbase Project name used as prefix for all resources. Must be 3-14 alphanumeric characters. Yes
EnvironmentType String production Environment type. Allowed values: development, staging, qa, production Yes

Project Parameter Details: The Project parameter serves as the primary identifier for your deployment and is used to name all AWS resources. It must follow these constraints:

  • Only alphanumeric characters (a-z, A-Z, 0-9)
  • Minimum 3 characters, maximum 14 characters
  • No special characters, spaces, or hyphens
  • Will be used in resource names like {Project}-{EnvironmentType}-api

Environment Type Impact: The EnvironmentType parameter affects resource sizing and configuration:

  • development: Minimal resources, single AZ deployment, smaller instance types
  • staging/qa: Medium resources, multi-AZ deployment, moderate instance types
  • production: Full resources, multi-AZ deployment, production-grade instance types

Domain and DNS Parameters

Parameter Type Default Description Required
RootDomainName String "" Root domain name (e.g., example.com). Leave empty to use ALB DNS names. No
HostedZoneId String "" Existing Route53 Hosted Zone ID. Leave empty to create a new one. No
ApiSubdomain String api Subdomain for API endpoints No
ConsoleSubdomain String console Subdomain for frontend console No
SocketSubdomain String socket Subdomain for WebSocket connections No

Domain Configuration Examples:

Without Custom Domain:

  • API: https://fleetbase-production-alb-123456789.us-east-1.elb.amazonaws.com
  • Console: https://d1234567890123.cloudfront.net
  • Socket: wss://fleetbase-production-alb-123456789.us-east-1.elb.amazonaws.com:8000

With Custom Domain (mycompany.com):

  • API: https://api.mycompany.com
  • Console: https://console.mycompany.com
  • Socket: wss://socket.mycompany.com

With Custom Subdomains:

RootDomainName: mycompany.com
ApiSubdomain: fleet-api
ConsoleSubdomain: fleet-app
SocketSubdomain: fleet-socket

Results in:

  • API: https://fleet-api.mycompany.com
  • Console: https://fleet-app.mycompany.com
  • Socket: wss://fleet-socket.mycompany.com

Database Configuration Parameters

Parameter Type Default Description Required
DatabaseInstanceType String db.t3.micro RDS instance type for the MySQL database No
DatabaseAllocatedStorage Number 20 Initial database storage in GB (20-65536) No
DatabaseMaxAllocatedStorage Number 100 Maximum database storage for auto-scaling in GB No
DatabaseBackupRetentionPeriod Number 7 Number of days to retain automated backups (0-35) No
DatabaseMultiAZ String false Enable Multi-AZ deployment for high availability No

Database Instance Type Recommendations:

Environment Instance Type vCPUs Memory Network Performance Monthly Cost*
Development db.t3.micro 2 1 GB Low to Moderate ~$15
Staging db.t3.small 2 2 GB Low to Moderate ~$30
Production (Small) db.t3.medium 2 4 GB Low to Moderate ~$60
Production (Medium) db.t3.large 2 8 GB Moderate ~$120
Production (Large) db.t3.xlarge 4 16 GB Moderate ~$240

*Approximate costs in US East (N. Virginia) region

Storage Configuration:

  • DatabaseAllocatedStorage: Initial storage allocation (minimum 20 GB for MySQL)
  • DatabaseMaxAllocatedStorage: Maximum storage for auto-scaling (prevents runaway storage costs)
  • Auto-scaling triggers when free storage falls below 10% or 10 GB (whichever is smaller)

Cache Configuration Parameters

Parameter Type Default Description Required
CacheInstanceType String cache.t3.micro ElastiCache Redis instance type No
CacheNumNodes Number 1 Number of cache nodes (1-20) No

Cache Instance Type Recommendations:

Environment Instance Type vCPUs Memory Network Performance Monthly Cost*
Development cache.t3.micro 2 0.5 GB Low to Moderate ~$15
Staging cache.t3.small 2 1.37 GB Low to Moderate ~$35
Production cache.t3.medium 2 3.22 GB Low to Moderate ~$70
High Traffic cache.m6g.large 2 6.38 GB Up to 10 Gbps ~$140

Container Configuration Parameters

Parameter Type Default Description Required
ApiDesiredCount Number 2 Desired number of API container instances No
ApiMaxCapacity Number 10 Maximum number of API containers for auto-scaling No
EventsDesiredCount Number 1 Desired number of event processing containers No
SchedulerDesiredCount Number 1 Desired number of scheduler containers No
SocketDesiredCount Number 1 Desired number of WebSocket containers No

Container Scaling Recommendations:

Environment API Desired API Max Events Scheduler Socket
Development 1 2 1 1 1
Staging 2 5 1 1 1
Production 3 10 2 1 2
High Traffic 5 20 3 1 3

Advanced Configuration Parameters

Parameter Type Default Description Required
EnableDetailedMonitoring String true Enable detailed CloudWatch monitoring No
LogRetentionDays Number 30 CloudWatch log retention period in days No
EnableVPCFlowLogs String false Enable VPC Flow Logs for network monitoring No
BackupRetentionPeriod Number 7 Database backup retention period in days No

Monitoring and Logging Options:

  • EnableDetailedMonitoring: Provides 1-minute metrics instead of 5-minute metrics
  • LogRetentionDays: Balances observability with storage costs (1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653 days)
  • EnableVPCFlowLogs: Useful for security analysis and network troubleshooting (additional costs apply)

Parameter Validation

The template includes built-in validation for all parameters:

  • String Length Validation: Project name length, domain name format
  • Numeric Range Validation: Storage sizes, retention periods, instance counts
  • Allowed Values: Environment types, instance types, boolean flags
  • Pattern Matching: Domain names, subdomain formats
  • Dependency Validation: Related parameters are validated together

Example Parameter File:

[
  {
    "ParameterKey": "Project",
    "ParameterValue": "myfleet"
  },
  {
    "ParameterKey": "EnvironmentType",
    "ParameterValue": "production"
  },
  {
    "ParameterKey": "RootDomainName",
    "ParameterValue": "mycompany.com"
  },
  {
    "ParameterKey": "DatabaseInstanceType",
    "ParameterValue": "db.t3.small"
  },
  {
    "ParameterKey": "ApiDesiredCount",
    "ParameterValue": "3"
  }
]

Use with: aws cloudformation create-stack --parameters file://parameters.json

πŸ“€ Outputs

After successful deployment, the CloudFormation stack provides the following outputs that contain important information for accessing and managing your Fleetbase deployment:

Application Access URLs

Output Name Description Example Value
ConsoleURL Frontend console application URL https://console.mycompany.com or https://d1234567890123.cloudfront.net
ApiURL Backend API base URL https://api.mycompany.com or https://fleetbase-prod-alb-123.us-east-1.elb.amazonaws.com
SocketURL WebSocket connection URL wss://socket.mycompany.com or wss://fleetbase-prod-alb-123.us-east-1.elb.amazonaws.com:8000

Infrastructure Resource Identifiers

Output Name Description Usage
VPCId Virtual Private Cloud identifier Network configuration, security group references
DatabaseEndpoint RDS MySQL database endpoint Application configuration, backup scripts
CacheEndpoint ElastiCache Redis endpoint Application configuration, monitoring
LoadBalancerDNS Application Load Balancer DNS name Direct API access, health checks
CloudFrontDistributionId CloudFront distribution identifier Cache invalidation, monitoring
S3BucketName Storage bucket name File upload configuration, backup scripts

Security and Access Information

Output Name Description Usage
ECSClusterName ECS cluster name Container management, scaling operations
DatabaseSecretArn Database credentials secret ARN Secure credential access
AppKeySecretArn Laravel application key secret ARN Application security configuration

Monitoring and Operations

Output Name Description Usage
LogGroupNames CloudWatch log group names Log analysis, troubleshooting
SQSQueueURL Message queue URL Job processing monitoring

Accessing Outputs:

# Get all stack outputs
aws cloudformation describe-stacks \
  --stack-name fleetbase-production \
  --query 'Stacks[0].Outputs'

# Get specific output value
aws cloudformation describe-stacks \
  --stack-name fleetbase-production \
  --query 'Stacks[0].Outputs[?OutputKey==`ConsoleURL`].OutputValue' \
  --output text

πŸ”§ Post-Deployment Configuration

After the CloudFormation stack completes successfully, several post-deployment steps are required to fully configure your Fleetbase installation.

Initial Application Setup

1. Access the Console Application: Navigate to the Console URL provided in the stack outputs. On first access, you'll be prompted to complete the initial setup wizard.

2. Create Administrator Account: The setup wizard will guide you through creating the first administrator account:

  • Choose a strong password following security best practices
  • Provide a valid email address for system notifications
  • Configure basic organization information

3. Configure Application Settings: Access the admin panel to configure essential settings:

  • Organization name and branding
  • Default time zone and locale settings
  • Email notification preferences
  • API rate limiting and security policies

Domain and SSL Configuration

For Custom Domain Deployments:

1. DNS Propagation Verification:

# Verify DNS records are properly configured
nslookup api.yourdomain.com
nslookup console.yourdomain.com
nslookup socket.yourdomain.com

# Check SSL certificate status
aws acm list-certificates --region us-east-1

2. SSL Certificate Validation:

  • AWS Certificate Manager automatically validates domain ownership
  • Validation typically completes within 5-10 minutes
  • Check the ACM console for validation status
  • Ensure DNS records are properly configured if validation fails

3. CloudFront Distribution Update: After SSL certificates are validated, CloudFront distributions are automatically updated. Monitor the distribution status:

aws cloudfront get-distribution --id YOUR_DISTRIBUTION_ID

Database Initialization

1. Database Migration Status: The deployment automatically runs database migrations, but you can verify completion:

# Access the API container to check migration status
aws ecs execute-command \
  --cluster fleetbase-production-cluster \
  --task TASK_ARN \
  --container api \
  --interactive \
  --command "php artisan migrate:status"

2. Seed Data (Optional): If you need to populate initial data:

# Run database seeders
aws ecs execute-command \
  --cluster fleetbase-production-cluster \
  --task TASK_ARN \
  --container api \
  --interactive \
  --command "php artisan db:seed"

File Storage Configuration

1. S3 Bucket Permissions: Verify that the application can access the S3 storage bucket:

# Test file upload functionality through the console
# Or use the API to test file operations
curl -X POST https://api.yourdomain.com/v1/files \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -F "[email protected]"

2. CDN Configuration: File uploads are automatically configured to use S3 with CloudFront for optimal delivery performance.

Queue and Background Job Configuration

1. SQS Queue Status: Verify that the message queue is properly configured:

# Check queue status
aws sqs get-queue-attributes \
  --queue-url YOUR_QUEUE_URL \
  --attribute-names All

2. Background Job Processing: The events service automatically processes background jobs. Monitor job processing:

# View events service logs
aws logs tail /aws/ecs/fleetbase-production-events --follow

Monitoring and Alerting Setup

1. CloudWatch Dashboard Creation: Create custom dashboards for monitoring key metrics:

  • API response times and error rates
  • Database connection and query performance
  • Cache hit ratios and memory usage
  • Container CPU and memory utilization

2. Alert Configuration: Set up CloudWatch alarms for critical metrics:

# Example: High API error rate alarm
aws cloudwatch put-metric-alarm \
  --alarm-name "Fleetbase-High-Error-Rate" \
  --alarm-description "Alert when API error rate exceeds 5%" \
  --metric-name "HTTPCode_Target_5XX_Count" \
  --namespace "AWS/ApplicationELB" \
  --statistic "Sum" \
  --period 300 \
  --threshold 10 \
  --comparison-operator "GreaterThanThreshold"

Security Hardening

1. Review Security Groups: Audit the automatically created security groups to ensure they meet your organization's security requirements:

# List security groups created by the stack
aws ec2 describe-security-groups \
  --filters "Name=group-name,Values=fleetbase-production-*"

2. Enable Additional Logging: Consider enabling additional AWS services for enhanced security monitoring:

  • AWS CloudTrail for API call logging
  • AWS Config for configuration compliance
  • AWS GuardDuty for threat detection

3. Backup Verification: Verify that automated backups are functioning correctly:

# Check RDS automated backups
aws rds describe-db-snapshots \
  --db-instance-identifier fleetbase-production-database \
  --snapshot-type automated

Performance Optimization

1. Auto Scaling Configuration: Monitor initial traffic patterns and adjust auto-scaling parameters if needed:

# Update ECS service desired count if needed
aws ecs update-service \
  --cluster fleetbase-production-cluster \
  --service fleetbase-production-api \
  --desired-count 3

2. Database Performance Tuning: Monitor database performance and consider enabling Performance Insights for detailed analysis:

# Enable Performance Insights
aws rds modify-db-instance \
  --db-instance-identifier fleetbase-production-database \
  --enable-performance-insights

Integration Configuration

1. Third-Party Service Integration: Configure integrations with external services through the admin panel:

  • Google Maps API for routing and geocoding
  • SMS providers for notifications
  • Email service configuration (SES is pre-configured)
  • Payment gateway setup if required

2. API Key Management: Generate and configure API keys for third-party integrations:

  • Create API keys for mobile applications
  • Configure webhook endpoints for external systems
  • Set up rate limiting policies for different API consumers

Backup and Disaster Recovery

1. Backup Strategy Implementation:

  • RDS automated backups are enabled by default
  • Consider implementing cross-region backup replication for critical deployments
  • Document recovery procedures and test them regularly

2. Disaster Recovery Planning:

  • Create runbooks for common failure scenarios
  • Test failover procedures in a staging environment
  • Document contact information and escalation procedures

πŸ“Š Monitoring and Logging

This CloudFormation template includes comprehensive monitoring and logging capabilities to ensure optimal performance and quick issue resolution.

CloudWatch Integration

Automatic Metrics Collection: The deployment automatically configures CloudWatch metrics for all services:

  • ECS Metrics: CPU utilization, memory usage, task count, service health
  • RDS Metrics: Database connections, CPU utilization, read/write IOPS, query performance
  • ElastiCache Metrics: Cache hit ratio, memory usage, connection count, evictions
  • Application Load Balancer Metrics: Request count, response times, error rates, target health
  • CloudFront Metrics: Cache hit ratio, origin latency, error rates, data transfer

Custom Application Metrics: The Fleetbase application sends custom metrics to CloudWatch:

  • API endpoint response times and error rates
  • Background job processing times and failure rates
  • User authentication success/failure rates
  • File upload/download metrics
  • WebSocket connection counts and message rates

Log Aggregation

Centralized Logging: All application logs are automatically sent to CloudWatch Logs with organized log groups:

/aws/ecs/fleetbase-{environment}-api          # API service logs
/aws/ecs/fleetbase-{environment}-events       # Background job logs
/aws/ecs/fleetbase-{environment}-scheduler    # Scheduled task logs
/aws/ecs/fleetbase-{environment}-socket       # WebSocket service logs
/aws/lambda/fleetbase-{environment}-console   # Console deployment logs

Log Analysis: Use CloudWatch Insights for advanced log analysis:

-- Find API errors in the last hour
fields @timestamp, @message
| filter @message like /ERROR/
| sort @timestamp desc
| limit 100

-- Monitor slow database queries
fields @timestamp, @message
| filter @message like /slow query/
| stats count() by bin(5m)

-- Track user authentication attempts
fields @timestamp, @message
| filter @message like /authentication/
| stats count() by result

Performance Monitoring

Application Performance Monitoring (APM): The template includes built-in performance monitoring capabilities:

  • Response Time Tracking: Monitor API endpoint response times with percentile analysis
  • Database Query Performance: Track slow queries and connection pool usage
  • Cache Performance: Monitor Redis hit ratios and memory utilization
  • Background Job Performance: Track job processing times and failure rates

Real-time Dashboards: Create CloudWatch dashboards for real-time monitoring:

# Create a comprehensive monitoring dashboard
aws cloudwatch put-dashboard \
  --dashboard-name "Fleetbase-Production-Overview" \
  --dashboard-body file://dashboard-config.json

Alerting and Notifications

Automated Alerting: The template includes pre-configured CloudWatch alarms for critical metrics:

  • High Error Rate: Alert when API error rate exceeds 5% over 5 minutes
  • Database Connection Issues: Alert when database connections exceed 80% of maximum
  • High CPU Usage: Alert when ECS task CPU usage exceeds 80% for 10 minutes
  • Memory Usage: Alert when container memory usage exceeds 85%
  • Cache Performance: Alert when Redis hit ratio drops below 90%

Custom Alert Configuration:

# Example: Create custom alert for high response times
aws cloudwatch put-metric-alarm \
  --alarm-name "Fleetbase-High-Response-Time" \
  --alarm-description "Alert when API response time exceeds 2 seconds" \
  --metric-name "TargetResponseTime" \
  --namespace "AWS/ApplicationELB" \
  --statistic "Average" \
  --period 300 \
  --threshold 2.0 \
  --comparison-operator "GreaterThanThreshold" \
  --evaluation-periods 2 \
  --alarm-actions "arn:aws:sns:us-east-1:123456789012:fleetbase-alerts"

πŸ›‘οΈ Security Considerations

This template implements multiple layers of security following AWS Well-Architected Framework security principles.

Network Security

VPC Isolation:

  • Private subnets for all backend services with no direct internet access
  • Public subnets only for load balancers and NAT gateways
  • Network ACLs providing subnet-level traffic filtering
  • VPC Flow Logs for network traffic analysis and security monitoring

Security Groups: The template creates least-privilege security groups:

# API Security Group - Only allows traffic from ALB
ApiSecurityGroup:
  - Port 8000: From ALB security group only
  - Port 443: Outbound HTTPS for external API calls
  - Port 3306: To database security group only
  - Port 6379: To cache security group only

# Database Security Group - Only allows traffic from application
DatabaseSecurityGroup:
  - Port 3306: From API, Events, and Scheduler security groups only
  - No outbound rules (managed service)

# Cache Security Group - Only allows traffic from application
CacheSecurityGroup:
  - Port 6379: From API, Events, and Scheduler security groups only
  - No outbound rules (managed service)

Data Encryption

Encryption at Rest:

  • RDS MySQL: Encrypted using AWS managed KMS keys
  • ElastiCache Redis: Encrypted using AWS managed KMS keys
  • S3 Storage: Server-side encryption with S3 managed keys (SSE-S3)
  • EBS Volumes: Encrypted for ECS Fargate tasks
  • CloudWatch Logs: Encrypted using CloudWatch Logs service encryption

Encryption in Transit:

  • HTTPS Everywhere: All web traffic encrypted with TLS 1.2+
  • Database Connections: SSL/TLS encryption for all database connections
  • Cache Connections: TLS encryption for Redis connections
  • Internal Service Communication: Encrypted communication between services

Identity and Access Management

Service Roles: The template creates specific IAM roles with minimal required permissions:

# ECS Task Role - Only permissions needed for application functionality
ECSTaskRole:
  Policies:
    - S3 access to storage bucket only
    - SQS access to application queues only
    - Secrets Manager access to application secrets only
    - CloudWatch Logs write access only

# ECS Execution Role - Only permissions needed for container management
ECSExecutionRole:
  Policies:
    - ECR image pull permissions
    - CloudWatch Logs creation
    - Secrets Manager read access for container environment variables

Secrets Management:

  • Database Credentials: Stored in AWS Secrets Manager with automatic rotation
  • Application Keys: Laravel APP_KEY stored in Secrets Manager
  • API Keys: Third-party API keys stored in Secrets Manager
  • No Hardcoded Secrets: All sensitive data retrieved at runtime

Application Security

Authentication and Authorization:

  • JWT Token Authentication: Secure token-based authentication with configurable expiration
  • Role-Based Access Control (RBAC): Granular permissions based on user roles
  • API Rate Limiting: Configurable rate limits to prevent abuse
  • CORS Configuration: Properly configured cross-origin resource sharing

Input Validation and Sanitization:

  • SQL Injection Prevention: Parameterized queries and ORM usage
  • XSS Protection: Input sanitization and output encoding
  • CSRF Protection: Cross-site request forgery tokens
  • File Upload Security: File type validation and virus scanning

Compliance and Auditing

Audit Logging:

  • CloudTrail Integration: All AWS API calls logged and monitored
  • Application Audit Logs: User actions and system changes logged
  • Database Audit Logs: Database access and query logging
  • Access Logs: Load balancer and CloudFront access logs

Compliance Features:

  • Data Retention Policies: Configurable log retention periods
  • Backup Encryption: All backups encrypted at rest
  • Access Controls: Principle of least privilege implemented throughout
  • Security Monitoring: Automated security event detection and alerting

πŸ”§ Troubleshooting

Common issues and their solutions for Fleetbase CloudFormation deployments.

Deployment Issues

Stack Creation Failures:

Issue: "CREATE_FAILED - The specified hosted zone does not exist"

# Solution: Verify hosted zone ID or remove the parameter to create a new one
aws route53 list-hosted-zones --query 'HostedZones[?Name==`yourdomain.com.`]'

Issue: "CREATE_FAILED - Certificate validation timeout"

# Solution: Check DNS records for certificate validation
aws acm describe-certificate --certificate-arn YOUR_CERT_ARN
# Ensure DNS validation records are properly configured

Issue: "CREATE_FAILED - Insufficient capacity in availability zone"

# Solution: Try different instance types or regions
aws ec2 describe-availability-zones --region us-east-1
# Consider using different instance types or regions with more capacity

Application Issues

Database Connection Problems:

Issue: "SQLSTATE[HY000] [1045] Access denied for user"

# Check database credentials in Secrets Manager
aws secretsmanager get-secret-value --secret-id fleetbase-production-db-password

# Verify security group allows database access
aws ec2 describe-security-groups --group-ids sg-xxxxxxxxx

Issue: "Database connection timeout"

# Check database status
aws rds describe-db-instances --db-instance-identifier fleetbase-production-database

# Verify network connectivity
aws ecs execute-command \
  --cluster fleetbase-production-cluster \
  --task TASK_ARN \
  --container api \
  --interactive \
  --command "telnet database-endpoint 3306"

Container Health Issues:

Issue: "Service tasks keep stopping and restarting"

# Check container logs for errors
aws logs tail /aws/ecs/fleetbase-production-api --follow

# Check ECS service events
aws ecs describe-services \
  --cluster fleetbase-production-cluster \
  --services fleetbase-production-api

Issue: "Load balancer health checks failing"

# Test health check endpoint directly
curl -I http://alb-dns-name/health

# Check target group health
aws elbv2 describe-target-health \
  --target-group-arn TARGET_GROUP_ARN

Performance Issues

High Response Times:

Issue: "API responses are slow"

# Check database performance
aws rds describe-db-instances \
  --db-instance-identifier fleetbase-production-database \
  --query 'DBInstances[0].PerformanceInsightsEnabled'

# Monitor cache hit ratio
aws cloudwatch get-metric-statistics \
  --namespace AWS/ElastiCache \
  --metric-name CacheHitRate \
  --dimensions Name=CacheClusterId,Value=fleetbase-production-cache \
  --start-time 2023-01-01T00:00:00Z \
  --end-time 2023-01-01T23:59:59Z \
  --period 3600 \
  --statistics Average

Issue: "High memory usage in containers"

# Check container resource utilization
aws ecs describe-services \
  --cluster fleetbase-production-cluster \
  --services fleetbase-production-api

# Scale up container resources if needed
aws ecs update-service \
  --cluster fleetbase-production-cluster \
  --service fleetbase-production-api \
  --desired-count 4

SSL and Domain Issues

SSL Certificate Problems:

Issue: "SSL certificate not trusted"

# Verify certificate status
aws acm list-certificates --region us-east-1
aws acm describe-certificate --certificate-arn YOUR_CERT_ARN

# Check DNS validation records
dig _acme-challenge.yourdomain.com TXT

Issue: "Domain not resolving correctly"

# Check DNS propagation
nslookup api.yourdomain.com
dig api.yourdomain.com A

# Verify Route53 records
aws route53 list-resource-record-sets --hosted-zone-id YOUR_ZONE_ID

Monitoring and Debugging

Log Analysis:

# Search for specific errors in logs
aws logs filter-log-events \
  --log-group-name /aws/ecs/fleetbase-production-api \
  --filter-pattern "ERROR" \
  --start-time 1609459200000

# Monitor real-time logs
aws logs tail /aws/ecs/fleetbase-production-api --follow

Performance Debugging:

# Check ECS service metrics
aws cloudwatch get-metric-statistics \
  --namespace AWS/ECS \
  --metric-name CPUUtilization \
  --dimensions Name=ServiceName,Value=fleetbase-production-api \
  --start-time 2023-01-01T00:00:00Z \
  --end-time 2023-01-01T23:59:59Z \
  --period 300 \
  --statistics Average,Maximum

Emergency Procedures:

Issue: "Complete service outage"

# Check overall stack status
aws cloudformation describe-stacks --stack-name fleetbase-production

# Verify all services are running
aws ecs list-services --cluster fleetbase-production-cluster
aws rds describe-db-instances --db-instance-identifier fleetbase-production-database

# Scale services if needed
aws ecs update-service \
  --cluster fleetbase-production-cluster \
  --service fleetbase-production-api \
  --desired-count 5

Getting Help

Support Resources:

  • Check the Fleetbase Documentation for application-specific issues
  • Review AWS service documentation for infrastructure problems
  • Use AWS Support for critical production issues
  • Community forums and GitHub issues for general questions

Diagnostic Information to Collect: When seeking help, gather the following information:

  • CloudFormation stack events and error messages
  • ECS service events and task definitions
  • Application logs from CloudWatch
  • Database and cache performance metrics
  • Network configuration and security group settings

🀝 Contributing

We welcome contributions to improve this CloudFormation template and make Fleetbase deployments even more robust and user-friendly.

How to Contribute

1. Fork the Repository

git clone https://github.com/your-org/fleetbase-cloudformation.git
cd fleetbase-cloudformation

2. Create a Feature Branch

git checkout -b feature/your-feature-name

3. Make Your Changes

  • Follow CloudFormation best practices and AWS Well-Architected principles
  • Test your changes thoroughly in multiple environments
  • Update documentation to reflect any changes
  • Add or update parameter descriptions and validation

4. Test Your Changes

# Validate CloudFormation template syntax
aws cloudformation validate-template --template-body file://template.yaml

# Test deployment in development environment
aws cloudformation create-stack \
  --stack-name fleetbase-test \
  --template-body file://template.yaml \
  --parameters ParameterKey=Project,ParameterValue=test \
               ParameterKey=EnvironmentType,ParameterValue=development \
  --capabilities CAPABILITY_NAMED_IAM

5. Submit a Pull Request

  • Provide a clear description of your changes
  • Include test results and validation screenshots
  • Reference any related issues or feature requests
  • Ensure all existing functionality remains intact

Contribution Guidelines

Code Standards:

  • Follow consistent YAML formatting and indentation
  • Use descriptive resource names and comments
  • Include parameter validation and constraints
  • Maintain backward compatibility when possible
  • Document all new parameters and outputs

Testing Requirements:

  • Test template deployment in at least two AWS regions
  • Verify both custom domain and non-domain configurations
  • Test with different parameter combinations
  • Validate all outputs and resource dependencies
  • Ensure clean stack deletion without orphaned resources

Documentation Standards:

  • Update README.md for any new features or parameters
  • Include examples and use cases for new functionality
  • Update troubleshooting section for known issues
  • Maintain accurate parameter tables and descriptions

Types of Contributions Welcomed

Infrastructure Improvements:

  • Enhanced security configurations
  • Performance optimizations
  • Cost optimization features
  • Additional AWS service integrations
  • Multi-region deployment support

Operational Enhancements:

  • Improved monitoring and alerting
  • Better backup and disaster recovery
  • Enhanced logging and debugging capabilities
  • Automated testing and validation scripts
  • CI/CD pipeline improvements

Documentation Improvements:

  • Clearer deployment instructions
  • Additional troubleshooting scenarios
  • Best practices and recommendations
  • Architecture diagrams and visualizations
  • Video tutorials and walkthroughs

Development Environment Setup

Prerequisites:

  • AWS CLI configured with appropriate permissions
  • Access to an AWS account for testing
  • Basic understanding of CloudFormation and AWS services
  • Familiarity with Fleetbase application architecture

Local Development:

# Install CloudFormation linting tools
pip install cfn-lint

# Validate template locally
cfn-lint template.yaml

# Use AWS CloudFormation Designer for visual editing
# https://console.aws.amazon.com/cloudformation/designer

Testing Environment:

  • Use separate AWS accounts or regions for testing
  • Implement proper resource tagging for cost tracking
  • Clean up test resources promptly to avoid unnecessary charges
  • Document test procedures and results

Reporting Issues

Bug Reports: When reporting bugs, please include:

  • CloudFormation template version
  • AWS region and account details (anonymized)
  • Complete error messages and stack events
  • Parameter values used (excluding sensitive data)
  • Steps to reproduce the issue
  • Expected vs. actual behavior

Feature Requests: When requesting features, please include:

  • Clear description of the desired functionality
  • Use case and business justification
  • Proposed implementation approach
  • Compatibility considerations
  • Documentation requirements

Security Issues: For security-related issues:

  • Do not create public GitHub issues
  • Email security concerns to [email protected]
  • Include detailed information about the vulnerability
  • Allow reasonable time for response and remediation

Community Guidelines

Code of Conduct:

  • Be respectful and inclusive in all interactions
  • Focus on constructive feedback and solutions
  • Help newcomers and answer questions patiently
  • Acknowledge contributions and give credit appropriately

Communication Channels:

  • GitHub Issues for bug reports and feature requests
  • GitHub Discussions for general questions and ideas
  • Pull Request comments for code review discussions
  • Email for security issues and private concerns

πŸ“„ License

This project is licensed under the AGPL v3 License - see the LICENSE file for details.

Third-Party Licenses

This CloudFormation template deploys and configures various AWS services and third-party software components. Please review the licenses for these components:

AWS Services:

  • All AWS services are subject to the AWS Customer Agreement
  • AWS service pricing applies according to current AWS pricing models
  • Data processing and storage subject to AWS data processing terms

Fleetbase Application:

Container Images:

  • fleetbase/fleetbase-api:latest - Subject to Fleetbase licensing terms
  • socketcluster/socketcluster:latest - MIT License
  • Base container images subject to their respective licenses

Usage Rights and Restrictions

Permitted Uses:

  • Deploy and operate Fleetbase in production environments
  • Modify the CloudFormation template for your specific needs
  • Distribute modified versions under the same MIT license
  • Use for commercial purposes without additional licensing fees
  • Create derivative works and improvements

Attribution Requirements:

  • Maintain copyright notices in distributed copies
  • Include the MIT license text in substantial portions
  • Credit original authors when redistributing
  • Link back to the original repository when appropriate

Disclaimer: This CloudFormation template is provided "as is" without warranty of any kind. Users are responsible for:

  • AWS service costs incurred during deployment and operation
  • Compliance with applicable laws and regulations
  • Security configuration and maintenance
  • Data backup and disaster recovery
  • Performance optimization and scaling

Support and Warranty

Community Support:

  • Community-driven support through GitHub Issues
  • Documentation and troubleshooting guides provided
  • Best-effort assistance from contributors and maintainers
  • No guaranteed response times or service level agreements

Commercial Support:

  • Professional support available through Fleetbase Inc.
  • Consulting services for custom deployments and integrations
  • Training and implementation assistance
  • Enterprise support contracts with guaranteed SLAs

No Warranty: The authors and contributors provide no warranty regarding:

  • Fitness for any particular purpose
  • Merchantability or quality
  • Non-infringement of third-party rights
  • Continuous availability or performance
  • Data integrity or security

Users deploy and operate this template at their own risk and responsibility.


πŸ™ Acknowledgments

This CloudFormation template was developed with contributions from the Fleetbase community and AWS experts. Special thanks to:

  • Fleetbase Team - For creating the open-source logistics platform
  • AWS Community - For CloudFormation best practices and patterns
  • Contributors - For testing, feedback, and improvements
  • Early Adopters - For real-world validation and use cases

Built With

References and Documentation


Ready to deploy Fleetbase on AWS? Start with our Quick Start guide or explore the deployment options to find the best approach for your use case.

About

Fleetbase AWS CloudFormation Template Documentation

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages