# AWS EC2 Deployment Guide

This guide will help you deploy the Auto Clicker application on an AWS EC2 instance with secure database credential management.

## Prerequisites

- AWS Account with appropriate permissions
- EC2 instance running Amazon Linux 2 or Ubuntu
- RDS MySQL database (already configured)
- Existing Parameter Store and Secrets Manager resources

## Step 1: EC2 Instance Setup

### 1.1 Create IAM Role

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"
            ]
        }
    ]
}
```

### 1.2 Attach Role to EC2 Instance

1. Go to EC2 Console
2. Select your instance
3. Actions → Security → Modify IAM role
4. Attach the role created in step 1.1

## Step 2: Install Dependencies

SSH into your EC2 instance and run:

```bash
# Update system
sudo apt update && sudo apt upgrade -y  # Ubuntu
# OR
sudo yum update -y  # Amazon Linux

# Install Python and pip
sudo apt install python3 python3-pip -y  # Ubuntu
# OR
sudo yum install python3 python3-pip -y  # Amazon Linux

# Install system dependencies for GUI applications (if running with display)
sudo apt install python3-tk -y  # Ubuntu

# Clone your repository
git clone <your-repository-url>
cd auto_clicker

# Install Python dependencies
pip3 install -r requirements.txt
```

## Step 3: Configure Environment

Set the environment variables:

```bash
# For development environment
export ENV=dev

# For QA environment
export ENV=qa

# Optional: Set AWS region (defaults to ap-southeast-2)
export AWS_REGION=ap-southeast-2

# Make environment variables persistent
echo "export ENV=qa" >> ~/.bashrc
echo "export AWS_REGION=ap-southeast-2" >> ~/.bashrc
source ~/.bashrc
```

## Step 4: Verify Configuration

Test the configuration:

```bash
cd mysql
python3 test_config.py
```

You should see output like:
```
✅ 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 5: Run the Application

```bash
# From the project root directory
python3 main.py
```

## Troubleshooting

### Common Issues

#### 1. "Failed to retrieve AWS credentials"

**Cause**: IAM role not attached or insufficient permissions

**Solution**:
- Verify IAM role is attached to EC2 instance
- Check IAM policy has correct permissions
- Ensure resource ARNs match your actual AWS resources

#### 2. "Parameter not found"

**Cause**: Parameter Store parameter doesn't exist or wrong environment

**Solution**:
- Verify parameter exists in AWS Parameter Store
- Check the parameter name matches the environment
- Ensure correct AWS region

#### 3. "Secret not found"

**Cause**: Secrets Manager secret doesn't exist or wrong name

**Solution**:
- Verify secret exists in AWS Secrets Manager
- Check the secret name matches the environment
- Ensure correct AWS region

#### 4. "Configuration validation failed"

**Cause**: Missing required fields in retrieved credentials

**Solution**:
- Check Parameter Store format: `host=value,port=value,database=value`
- Check Secrets Manager format: `{"username": "user", "password": "pass"}`
- Verify all required fields are present

### Debug Commands

```bash
# Check IAM role attached to instance
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/

# Check environment variables
env | grep -E "(ENV|AWS)"

# Test AWS credentials manually
aws sts get-caller-identity

# Test Parameter Store access
aws ssm get-parameter --name "rdsDetails" --region ap-southeast-2

# Test Secrets Manager access
aws secretsmanager get-secret-value --secret-id "rds!cluster-91f2520d-663f-4a7b-9f72-cc0878bdf354" --region ap-southeast-2
```

## 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

## Monitoring

Consider setting up CloudWatch logs and alarms for:
- Failed authentication attempts
- Unusual database access patterns
- Application errors

## Environment-Specific Configuration

### Development
- Uses secret: `rds!cluster-91f2520d-663f-4a7b-9f72-cc0878bdf354`
- Uses parameter: `rdsDetails`
- Set: `ENV=dev`

### QA
- Uses secret: `rds!cluster-252d62f4-d31e-4fe7-a51e-7f96a6a82e3f`
- Uses parameter: `rdsDetailsQA`
- Set: `ENV=qa`

## Support

For issues with this deployment:
1. Check the troubleshooting section above
2. Review AWS CloudTrail logs for API access issues
3. Check application logs for detailed error messages
4. Verify all prerequisites are met
