# Custom PHP Framework - Infrastructure Automation

Modern, secure Ansible infrastructure automation for the Custom PHP Framework with PHP 8.4 optimization.

## 🏗️ Architecture Overview

### Security-First Design
- **SSH Hardening**: Secure SSH configuration with key-based authentication
- **Firewall Protection**: UFW firewall with fail2ban intrusion detection
- **SSL/TLS**: Let's Encrypt certificates with modern cipher suites
- **Security Headers**: Comprehensive HTTP security headers
- **System Hardening**: Kernel parameters, audit logging, and security monitoring

### Docker-Optimized Runtime
- **PHP 8.4**: Optimized Docker containers with custom PHP configuration
- **Security Profiles**: AppArmor and seccomp security profiles
- **Resource Limits**: Memory and CPU constraints for production workloads
- **Health Checks**: Automated container health monitoring

### Production-Ready Infrastructure
- **Environment Separation**: Development, staging, and production configurations
- **Monitoring**: System health checks and performance monitoring
- **Backup System**: Automated backup with encryption and retention policies
- **Log Management**: Centralized logging with rotation and monitoring

## 🚀 Quick Start

### Prerequisites

```bash
# Install Ansible
pip install ansible

# Install required collections
ansible-galaxy collection install community.general
ansible-galaxy collection install community.crypto
ansible-galaxy collection install community.docker
```

### Initial Setup

1. **Configure Ansible Vault**:
```bash
cd deployment/infrastructure
echo "your_vault_password" > .vault_pass
chmod 600 .vault_pass

# Encrypt sensitive variables
ansible-vault encrypt group_vars/all/vault.yml
```

2. **Update Inventory**:
   - Edit `inventories/production/hosts.yml` with your server details
   - Update domain and SSL email configuration

3. **Deploy Infrastructure**:
```bash
# Production deployment
ansible-playbook -i inventories/production site.yml

# Staging deployment
ansible-playbook -i inventories/staging site.yml
```

## 📁 Directory Structure

```
deployment/infrastructure/
├── ansible.cfg                 # Ansible configuration
├── site.yml                   # Main deployment playbook
├── inventories/               # Environment-specific inventory
│   ├── production/
│   ├── staging/
│   └── development/
├── group_vars/               # Global variables
│   └── all/
├── roles/                    # Ansible roles
│   ├── base-security/        # Security hardening
│   ├── docker-runtime/       # Docker with PHP 8.4
│   ├── nginx-proxy/          # Nginx reverse proxy
│   └── monitoring/           # Health monitoring
└── playbooks/               # Additional playbooks
```

## 🔒 Security Features

### SSH Hardening
- Key-based authentication only
- Strong cipher suites and key exchange algorithms
- Connection rate limiting
- Security banners and access logging

### Firewall Configuration
- Default deny policy with specific allow rules
- Rate limiting for SSH connections
- Protection for Docker containers
- Environment-specific rule sets

### SSL/TLS Security
- Let's Encrypt certificates with auto-renewal
- Modern TLS protocols (1.2, 1.3)
- HSTS with preloading
- OCSP stapling enabled

### Application Security
- Security headers (CSP, HSTS, X-Frame-Options)
- Rate limiting for API endpoints
- Input validation and sanitization
- OWASP security compliance

## 🐳 Docker Configuration

### PHP 8.4 Optimization
- Custom PHP 8.4 container with security hardening
- OPcache configuration for production performance
- Memory and execution time limits
- Extension management for framework requirements

### Container Security
- Non-root user execution
- Read-only root filesystem where possible
- Security profiles (AppArmor, seccomp)
- Resource constraints and health checks

### Network Security
- Custom bridge networks with isolation
- No inter-container communication by default
- Encrypted internal communication
- External access controls

## 📊 Monitoring & Health Checks

### System Monitoring
- CPU, memory, and disk usage monitoring
- Load average and process monitoring
- Network and I/O performance tracking
- Automated alerting for threshold breaches

### Application Health Checks
- HTTP endpoint monitoring
- Database connectivity checks
- Framework-specific health validation
- Container health verification

### Log Management
- Centralized log collection and rotation
- Error pattern detection and alerting
- Security event logging and monitoring
- Performance metrics collection

## 🔧 Environment Configuration

### Production Environment
- High security settings with strict firewall
- Performance optimizations enabled
- Comprehensive monitoring and alerting
- Daily automated backups

### Staging Environment
- Relaxed security for testing
- Debug mode enabled
- Basic monitoring
- Weekly backups

### Development Environment
- Minimal security restrictions
- Full debugging capabilities
- No production optimizations
- No automated backups

## 📋 Deployment Playbooks

### Main Infrastructure (`site.yml`)
Deploys complete infrastructure stack:
- Base security hardening
- Docker runtime environment
- Nginx reverse proxy with SSL
- System monitoring and health checks

### Application Deployment (`playbooks/deploy-application.yml`)
Handles application-specific deployment:
- Code deployment from Git repository
- Dependency installation (Composer, NPM)
- Database migrations
- Asset compilation and optimization
- Service restarts and health verification

## 🛠️ Management Commands

### Infrastructure Management
```bash
# Deploy to production
ansible-playbook -i inventories/production site.yml

# Deploy specific role
ansible-playbook -i inventories/production site.yml --tags security

# Run health checks
ansible-playbook -i inventories/production site.yml --tags verification

# Update SSL certificates
ansible-playbook -i inventories/production site.yml --tags ssl
```

### Application Management
```bash
# Deploy application code
ansible-playbook -i inventories/production playbooks/deploy-application.yml

# Deploy specific branch
ansible-playbook -i inventories/production playbooks/deploy-application.yml -e deploy_branch=feature/new-feature
```

### Security Operations
```bash
# Security audit
ansible-playbook -i inventories/production site.yml --tags audit

# Update security configurations
ansible-playbook -i inventories/production site.yml --tags security

# Restart security services
ansible-playbook -i inventories/production site.yml --tags security,restart
```

## 🔐 Ansible Vault Usage

### Encrypting Secrets
```bash
# Encrypt vault file
ansible-vault encrypt group_vars/all/vault.yml

# Edit encrypted file
ansible-vault edit group_vars/all/vault.yml

# View encrypted file
ansible-vault view group_vars/all/vault.yml
```

### Running Playbooks with Vault
```bash
# Using vault password file (configured in ansible.cfg)
ansible-playbook site.yml

# Prompt for vault password
ansible-playbook site.yml --ask-vault-pass

# Using vault password file explicitly
ansible-playbook site.yml --vault-password-file .vault_pass
```

## 📝 Customization

### Adding Custom Roles
1. Create role directory structure
2. Define role metadata in `meta/main.yml`
3. Add role to main playbook
4. Test in development environment

### Environment-Specific Variables
- Update inventory files for environment-specific settings
- Modify group variables for global changes
- Use vault files for sensitive information

### SSL Certificate Management
- Let's Encrypt: Automatic certificate generation and renewal
- Self-signed: For development and testing environments
- Custom certificates: Place in appropriate directories

## 🚨 Troubleshooting

### Common Issues

**SSH Connection Failures**:
- Verify SSH key configuration
- Check firewall rules and fail2ban status
- Ensure user has proper sudo privileges

**SSL Certificate Problems**:
- Verify DNS resolution for domain
- Check Let's Encrypt rate limits
- Ensure port 80 is accessible for validation

**Docker Container Issues**:
- Check Docker daemon status and logs
- Verify image build and pull permissions
- Review container resource limits

**Performance Problems**:
- Monitor system resources and logs
- Check application and database performance
- Review caching and optimization settings

### Getting Help

For issues specific to the Custom PHP Framework infrastructure:
1. Check Ansible logs in `/var/log/ansible.log`
2. Review system logs for specific services
3. Use the monitoring dashboard for system health
4. Contact the development team at kontakt@michaelschiemer.de

## 📄 License

This infrastructure automation is part of the Custom PHP Framework project.
Licensed under MIT License - see LICENSE file for details.

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch
3. Test changes in development environment
4. Submit a pull request with detailed description

---

**Domain**: michaelschiemer.de  
**Environment**: Production-ready with PHP 8.4 optimization  
**Security**: Enterprise-grade hardening and monitoring  
**Maintainer**: kontakt@michaelschiemer.de