# AWS EC2 + Bitbucket Deployment Guide

Complete guide for deploying the Auto Clicker application from Bitbucket to AWS EC2 Ubuntu VM.

## 📋 Table of Contents

- [Prerequisites](#prerequisites)
- [Step 1: EC2 Instance Configuration](#step-1-ec2-instance-configuration)
- [Step 2: Connect to EC2 Instance](#step-2-connect-to-ec2-instance)
- [Step 3: Install System Dependencies](#step-3-install-system-dependencies)
- [Step 4: Configure Bitbucket Access](#step-4-configure-bitbucket-access)
- [Step 5: Clone Repository](#step-5-clone-repository)
- [Step 6: Set Up Python Environment](#step-6-set-up-python-environment)
- [Step 7: Configure Environment Variables](#step-7-configure-environment-variables)
- [Step 8: Configure AWS Credentials](#step-8-configure-aws-credentials)
- [Step 9: Test Configuration](#step-9-test-configuration)
- [Step 10: Run the Application](#step-10-run-the-application)
- [Automated Deployment](#automated-deployment)
- [Troubleshooting](#troubleshooting)
- [Maintenance](#maintenance)

## Prerequisites

- ✅ AWS Account with appropriate permissions
- ✅ EC2 Ubuntu instance running
- ✅ Bitbucket repository with auto-clicker code
- ✅ RDS MySQL database configured
- ✅ AWS Parameter Store and Secrets Manager resources set up

## Step 1: EC2 Instance Configuration

### IAM Role Setup

Create an IAM role for your EC2 instance with the following policy:

```json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "secretsmanager:GetSecretValue"
            ],
            "Resource": [
                "arn:aws:secretsmanager:ap-southeast-2:*:secret:rds!cluster-91f2520d-663f-4a7b-9f72-cc0878bdf354*",
                "arn:aws:secretsmanager:ap-southeast-2:*:secret:rds!cluster-252d62f4-d31e-4fe7-a51e-7f96a6a82e3f*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "ssm:GetParameter"
            ],
            "Resource": [
                "arn:aws:ssm:ap-southeast-2:*:parameter/rdsDetails",
                "arn:aws:ssm:ap-southeast-2:*:parameter/rdsDetailsQA"
            ]
        }
    ]
}
```

### Security Group Configuration

Configure your EC2 security group with these rules:

| Type | Protocol | Port | Source | Description |
|------|----------|------|---------|-------------|
| SSH | TCP | 22 | Your IP | SSH access |
| HTTP | TCP | 80 | 0.0.0.0/0 | Web interface (if needed) |
| HTTPS | TCP | 443 | 0.0.0.0/0 | Secure web interface (if needed) |
| Custom | TCP | Custom | As needed | Application specific ports |

### Attach IAM Role to EC2

1. Go to EC2 Console
2. Select your instance
3. Actions → Security → Modify IAM role
4. Attach the role created above

## Step 2: Connect to EC2 Instance

```bash
# Connect to your EC2 instance
ssh -i your-key.pem ubuntu@your-ec2-public-ip
```

## Step 3: Install System Dependencies

```bash
# Update the system
sudo apt update && sudo apt upgrade -y

# Install essential packages
sudo apt install -y git python3 python3-pip python3-venv python3-tk

# Install additional dependencies for GUI applications
sudo apt install -y xvfb x11-utils libxkbcommon-x11-0

# Install AWS CLI
sudo apt install -y awscli

# Verify installations
python3 --version
git --version
aws --version
```

## Step 4: Configure Bitbucket Access

You have two options for accessing your Bitbucket repository:

### Option A: SSH Key Authentication (Recommended)

```bash
# Generate SSH key pair
ssh-keygen -t rsa -b 4096 -C "your-email@example.com"

# Display the public key
cat ~/.ssh/id_rsa.pub
```

**Then:**
1. Copy the public key output
2. Go to Bitbucket → Settings → SSH keys
3. Add the public key to your Bitbucket account

**Test SSH connection:**
```bash
ssh -T git@bitbucket.org
```

### Option B: HTTPS with App Password

```bash
# Configure Git with your Bitbucket credentials
git config --global user.name "Your Name"
git config --global user.email "your-email@example.com"
```

**For HTTPS, you'll need a Bitbucket App Password:**
1. Go to Bitbucket → Personal settings → App passwords
2. Create a new app password with repository permissions
3. Use this password when cloning (not your account password)

## Step 5: Clone Repository

```bash
# Navigate to home directory
cd ~

# Clone using SSH (if you set up SSH keys)
git clone git@bitbucket.org:your-username/auto_clicker.git

# OR clone using HTTPS (if using app password)
git clone https://your-username@bitbucket.org/your-username/auto_clicker.git

# Navigate to the project directory
cd auto_clicker
```

## Step 6: Set Up Python Environment

```bash
# Create a virtual environment
python3 -m venv venv

# Activate the virtual environment
source venv/bin/activate

# Install project dependencies
pip install -r requirements.txt

# Install additional dependencies if needed
pip install boto3 mysql-connector-python python-dotenv
```

## Step 7: Configure Environment Variables

```bash
# Set environment variables for your application
export ENV=dev  # or 'qa' for QA environment
export AWS_REGION=ap-southeast-2

# Make environment variables persistent
echo "export ENV=dev" >> ~/.bashrc
echo "export AWS_REGION=ap-southeast-2" >> ~/.bashrc
echo "source ~/auto_clicker/venv/bin/activate" >> ~/.bashrc

# Reload bash configuration
source ~/.bashrc
```

## Step 8: Configure AWS Credentials

Since you're using IAM roles, the AWS credentials should be automatically available:

```bash
# Test AWS credentials
aws sts get-caller-identity

# Test Parameter Store access
aws ssm get-parameter --name "rdsDetails" --region ap-southeast-2

# Test Secrets Manager access (use your actual secret ID)
aws secretsmanager get-secret-value --secret-id "rds!cluster-91f2520d-663f-4a7b-9f72-cc0878bdf354" --region ap-southeast-2
```

## Step 9: Test Configuration

```bash
# Test database configuration
cd ~/auto_clicker/mysql
python3 test_config.py
```

**Expected output:**
```
✅ Using AWS credentials for environment: dev
✅ Configuration loaded successfully!
📊 Database: auto_clicker
🏠 Host: your-rds-endpoint.amazonaws.com
👤 User: your_db_user
🔌 Port: 3306
```

## Step 10: Run the Application

```bash
# Navigate back to project root
cd ~/auto_clicker

# Ensure virtual environment is activated
source venv/bin/activate

# Run the application
python3 main.py
```

## Automated Deployment

For quick deployment, use the provided automation script:

```bash
# Make the script executable
chmod +x deploy_ec2.sh

# Run the deployment script
./deploy_ec2.sh
```

The script will:
- Update system packages
- Install all dependencies
- Configure Git access
- Set up Python environment
- Test AWS and database connections
- Create a systemd service (optional)

## Troubleshooting

### Common Issues and Solutions

#### 1. Git Authentication Issues

**SSH Issues:**
```bash
# Test SSH connection
ssh -T git@bitbucket.org

# Check SSH key is added
ssh-add -l
```

**HTTPS Issues:**
```bash
# Use app password instead of account password
git clone https://username:app-password@bitbucket.org/workspace/repository.git
```

#### 2. AWS Credentials Issues

**Check IAM Role:**
```bash
# Check if IAM role is attached
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/

# Check environment variables
env | grep -E "(ENV|AWS)"
```

**Test AWS Services:**
```bash
# Test AWS CLI
aws sts get-caller-identity

# Test specific services
aws ssm get-parameter --name "rdsDetails" --region ap-southeast-2
aws secretsmanager list-secrets --region ap-southeast-2
```

#### 3. Python Dependencies Issues

```bash
# Update pip and reinstall
pip install --upgrade pip
pip install -r requirements.txt --force-reinstall

# Check virtual environment
which python
which pip
```

#### 4. Display Issues (for GUI applications)

```bash
# Set up virtual display for headless operation
export DISPLAY=:0
Xvfb :0 -screen 0 1024x768x24 &

# Test display
echo $DISPLAY
```

#### 5. Database Connection Issues

**Check Database Configuration:**
```bash
# Verify Parameter Store values
aws ssm get-parameter --name "rdsDetails" --region ap-southeast-2

# Verify Secrets Manager values
aws secretsmanager get-secret-value --secret-id "your-secret-id" --region ap-southeast-2

# Test database connection manually
cd mysql
python3 test_mysql.py
```

#### 6. Permission Issues

```bash
# Fix file permissions
chmod +x deploy_ec2.sh
chmod +r requirements.txt

# Fix directory permissions
sudo chown -R ubuntu:ubuntu ~/auto_clicker
```

### Debug Commands

```bash
# Check system status
systemctl status autoclicker

# View application logs
sudo journalctl -u autoclicker -f

# Check disk space
df -h

# Check memory usage
free -h

# Check running processes
ps aux | grep python
```

## Maintenance

### Keeping Code Updated

```bash
# Navigate to project directory
cd ~/auto_clicker

# Pull latest changes
git pull origin main

# Update dependencies if needed
source venv/bin/activate
pip install -r requirements.txt

# Restart service if running as systemd service
sudo systemctl restart autoclicker
```

### Monitoring

**Set up basic monitoring:**
```bash
# Check application status
systemctl status autoclicker

# Monitor logs in real-time
sudo journalctl -u autoclicker -f

# Check system resources
htop
```

### Backup

**Regular backup routine:**
```bash
# Backup configuration files
tar -czf ~/backup-$(date +%Y%m%d).tar.gz ~/auto_clicker

# Backup database (if needed)
mysqldump -h your-rds-endpoint -u username -p auto_clicker > backup.sql
```

## Security Best Practices

1. **Least Privilege**: Only grant minimum required permissions
2. **Resource Specific**: Use specific resource ARNs, not wildcards
3. **Environment Separation**: Use different secrets for dev/qa/prod
4. **Regular Rotation**: Rotate database passwords regularly
5. **Monitoring**: Enable CloudTrail for API access monitoring
6. **SSH Keys**: Use SSH keys instead of passwords
7. **Security Groups**: Restrict access to necessary ports only

## Environment-Specific Configuration

### Development Environment
- **Secret**: `rds!cluster-91f2520d-663f-4a7b-9f72-cc0878bdf354`
- **Parameter**: `rdsDetails`
- **Environment Variable**: `ENV=dev`

### QA Environment
- **Secret**: `rds!cluster-252d62f4-d31e-4fe7-a51e-7f96a6a82e3f`
- **Parameter**: `rdsDetailsQA`
- **Environment Variable**: `ENV=qa`

## Quick Reference Commands

### Daily Operations
```bash
# Connect to EC2
ssh -i your-key.pem ubuntu@your-ec2-ip

# Navigate and activate environment
cd ~/auto_clicker && source venv/bin/activate

# Run application
python3 main.py

# Update from Bitbucket
git pull

# Check application status
systemctl status autoclicker
```

### Service Management
```bash
# Start service
sudo systemctl start autoclicker

# Stop service
sudo systemctl stop autoclicker

# Restart service
sudo systemctl restart autoclicker

# Enable auto-start
sudo systemctl enable autoclicker

# Check service logs
sudo journalctl -u autoclicker -f
```

## Support

For deployment issues:
1. Check this troubleshooting guide
2. Review AWS CloudTrail logs for API access issues
3. Check application logs: `sudo journalctl -u autoclicker -f`
4. Verify all prerequisites are met
5. Test each component individually

---

**📝 Note**: Replace placeholders like `your-username`, `your-ec2-public-ip`, and AWS resource ARNs with your actual values.

**🔄 Last Updated**: $(date)
