diff --git a/.github/workflows/README.md b/.github/workflows/README.md new file mode 100644 index 0000000..0638795 --- /dev/null +++ b/.github/workflows/README.md @@ -0,0 +1,139 @@ +# GitHub Actions Workflows + +This directory contains GitHub Actions workflows for automated infrastructure deployment and management. + +## Terraform DigitalOcean Infrastructure Workflow + +The `terraform-digitalocean.yml` workflow provides manual deployment of infrastructure to DigitalOcean using Terraform. + +### Features + +- **Manual Trigger**: Workflow can be triggered manually with customizable parameters +- **Multiple Environments**: Support for dev, staging, and production environments +- **Multiple Regions**: Support for all major DigitalOcean regions +- **Security Scanning**: Integrated Trivy vulnerability scanning +- **Plan Review**: Terraform plans are uploaded as artifacts and commented on issues +- **Comprehensive Logging**: Detailed logging and notification system + +### Prerequisites + +1. **DigitalOcean API Token**: You need a DigitalOcean API token with appropriate permissions +2. **GitHub Secrets**: Configure the following secrets in your GitHub repository: + - `DIGITALOCEAN_TOKEN`: Your DigitalOcean API token + +### Setup Instructions + +1. **Create DigitalOcean API Token**: + - Go to [DigitalOcean API Tokens](https://cloud.digitalocean.com/account/api/tokens) + - Click "Generate New Token" + - Give it a name (e.g., "GitHub Actions Terraform") + - Select "Write" scope + - Copy the token + +2. **Add GitHub Secret**: + - Go to your GitHub repository + - Navigate to Settings → Secrets and variables → Actions + - Click "New repository secret" + - Name: `DIGITALOCEAN_TOKEN` + - Value: Paste your DigitalOcean API token + +### Usage + +1. **Trigger the Workflow**: + - Go to the "Actions" tab in your GitHub repository + - Select "Terraform DigitalOcean Infrastructure" + - Click "Run workflow" + +2. **Configure Parameters**: + - **Environment**: Choose dev, staging, or prod + - **Action**: Choose plan, apply, or destroy + - **Region**: Select your preferred DigitalOcean region + - **Domain Name**: (Optional) Enter your domain for production + +3. **Workflow Actions**: + - **Plan**: Creates a Terraform plan without applying changes + - **Apply**: Applies the Terraform configuration to create/update infrastructure + - **Destroy**: Removes all infrastructure (use with caution) + +### Workflow Steps + +1. **Checkout**: Downloads the repository code +2. **Setup Terraform**: Installs Terraform with the specified version +3. **Format Check**: Validates Terraform code formatting +4. **Init**: Initializes Terraform working directory +5. **Validate**: Validates Terraform configuration +6. **Plan**: Creates execution plan (for plan/apply actions) +7. **Apply/Destroy**: Executes Terraform commands +8. **Security Scan**: Runs Trivy vulnerability scanner +9. **Notify**: Provides status notifications + +### Security Features + +- **Secret Management**: Uses GitHub secrets for sensitive data +- **Vulnerability Scanning**: Integrated Trivy scanner for security issues +- **Plan Review**: Plans are saved as artifacts for review +- **Environment Isolation**: Separate configurations for different environments + +### Supported DigitalOcean Regions + +- `nyc1` - New York 1 +- `nyc3` - New York 3 +- `sfo2` - San Francisco 2 +- `sfo3` - San Francisco 3 +- `ams2` - Amsterdam 2 +- `ams3` - Amsterdam 3 +- `fra1` - Frankfurt 1 +- `lon1` - London 1 +- `sgp1` - Singapore 1 +- `tor1` - Toronto 1 + +### Infrastructure Components + +The workflow deploys the following DigitalOcean resources: + +- **Container Registry**: For storing Docker images +- **App Platform**: For running containerized applications +- **Database Cluster**: PostgreSQL database (production only) +- **Load Balancer**: For traffic distribution (production only) +- **Firewall**: Security rules for network access +- **Spaces Bucket**: Object storage for logs +- **Monitoring**: CPU and memory alerts +- **Domain & DNS**: Custom domain configuration (production only) + +### Troubleshooting + +1. **Authentication Errors**: + - Verify your `DIGITALOCEAN_TOKEN` secret is correctly set + - Ensure the token has "Write" permissions + +2. **Terraform Errors**: + - Check the workflow logs for detailed error messages + - Verify your Terraform configuration files are valid + - Ensure all required variables are provided + +3. **Resource Limits**: + - Check your DigitalOcean account limits + - Verify you have sufficient credits/balance + +### Best Practices + +1. **Always Plan First**: Run a plan before applying changes +2. **Use Separate Environments**: Keep dev, staging, and prod isolated +3. **Review Changes**: Always review Terraform plans before applying +4. **Monitor Costs**: Keep track of DigitalOcean resource usage +5. **Backup State**: Consider using remote state storage for production + +### Cost Optimization + +- Use appropriate instance sizes for each environment +- Enable auto-scaling for production workloads +- Set up monitoring alerts for resource usage +- Regularly review and clean up unused resources + +### Support + +For issues or questions: +1. Check the workflow logs for error details +2. Review the Terraform configuration files +3. Consult the DigitalOcean documentation +4. Open an issue in the repository \ No newline at end of file diff --git a/.github/workflows/terraform-digitalocean.yml b/.github/workflows/terraform-digitalocean.yml new file mode 100644 index 0000000..d635daa --- /dev/null +++ b/.github/workflows/terraform-digitalocean.yml @@ -0,0 +1,189 @@ +name: Terraform DigitalOcean Infrastructure + +on: + workflow_dispatch: + inputs: + environment: + description: 'Environment to deploy to' + required: true + default: 'dev' + type: choice + options: + - dev + - staging + - prod + action: + description: 'Terraform action to perform' + required: true + default: 'plan' + type: choice + options: + - plan + - apply + - destroy + region: + description: 'DigitalOcean region' + required: true + default: 'nyc1' + type: choice + options: + - nyc1 + - nyc3 + - sfo2 + - sfo3 + - ams2 + - ams3 + - fra1 + - lon1 + - sgp1 + - tor1 + domain_name: + description: 'Domain name (optional, for production)' + required: false + type: string + default: '' + +env: + TF_VERSION: "1.5.0" + TF_WORKING_DIR: "./terraform" + +jobs: + terraform: + name: 'Terraform' + runs-on: ubuntu-latest + + defaults: + run: + working-directory: ${{ env.TF_WORKING_DIR }} + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Terraform + uses: hashicorp/setup-terraform@v3 + with: + terraform_version: ${{ env.TF_VERSION }} + + - name: Terraform Format Check + run: terraform fmt -check -recursive + if: ${{ github.event.inputs.action == 'plan' || github.event.inputs.action == 'apply' }} + + - name: Terraform Init + run: terraform init + env: + TF_VAR_cloud_provider: "digitalocean" + TF_VAR_environment: ${{ github.event.inputs.environment }} + TF_VAR_region: ${{ github.event.inputs.region }} + TF_VAR_domain_name: ${{ github.event.inputs.domain_name }} + + - name: Terraform Validate + run: terraform validate + if: ${{ github.event.inputs.action == 'plan' || github.event.inputs.action == 'apply' }} + + - name: Terraform Plan + id: plan + run: | + terraform plan \ + -var="cloud_provider=digitalocean" \ + -var="environment=${{ github.event.inputs.environment }}" \ + -var="region=${{ github.event.inputs.region }}" \ + -var="domain_name=${{ github.event.inputs.domain_name }}" \ + -out=tfplan + if: ${{ github.event.inputs.action == 'plan' || github.event.inputs.action == 'apply' }} + + - name: Terraform Plan Status + if: steps.plan.outcome == 'failure' + run: exit 1 + + - name: Terraform Apply + if: ${{ github.event.inputs.action == 'apply' }} + run: terraform apply -auto-approve tfplan + env: + DIGITALOCEAN_TOKEN: ${{ secrets.DIGITALOCEAN_TOKEN }} + + - name: Terraform Destroy + if: ${{ github.event.inputs.action == 'destroy' }} + run: terraform destroy -auto-approve + env: + DIGITALOCEAN_TOKEN: ${{ secrets.DIGITALOCEAN_TOKEN }} + + - name: Upload Terraform Plan + uses: actions/upload-artifact@v4 + if: ${{ github.event.inputs.action == 'plan' }} + with: + name: terraform-plan + path: ${{ env.TF_WORKING_DIR }}/tfplan + + - name: Comment Plan Results + if: ${{ github.event.inputs.action == 'plan' }} + uses: actions/github-script@v7 + with: + script: | + const fs = require('fs'); + const plan = fs.readFileSync('${{ env.TF_WORKING_DIR }}/tfplan', 'utf8'); + const comment = `## Terraform Plan Results + + **Environment:** ${{ github.event.inputs.environment }} + **Region:** ${{ github.event.inputs.region }} + **Action:** ${{ github.event.inputs.action }} + + \`\`\`hcl + ${plan} + \`\`\` + `; + + github.rest.issues.createComment({ + issue_number: context.issue.number, + owner: context.repo.owner, + repo: context.repo.repo, + body: comment + }); + + security-scan: + name: 'Security Scan' + runs-on: ubuntu-latest + needs: terraform + if: ${{ github.event.inputs.action == 'apply' }} + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Run Trivy vulnerability scanner + uses: aquasecurity/trivy-action@master + with: + scan-type: 'fs' + scan-ref: '.' + format: 'sarif' + output: 'trivy-results.sarif' + + - name: Upload Trivy scan results to GitHub Security tab + uses: github/codeql-action/upload-sarif@v3 + if: always() + with: + sarif_file: 'trivy-results.sarif' + + notify: + name: 'Notify' + runs-on: ubuntu-latest + needs: [terraform, security-scan] + if: always() + + steps: + - name: Notify on Success + if: ${{ needs.terraform.result == 'success' && needs.security-scan.result == 'success' }} + run: | + echo "✅ Terraform deployment completed successfully!" + echo "Environment: ${{ github.event.inputs.environment }}" + echo "Region: ${{ github.event.inputs.region }}" + echo "Action: ${{ github.event.inputs.action }}" + + - name: Notify on Failure + if: ${{ needs.terraform.result == 'failure' || needs.security-scan.result == 'failure' }} + run: | + echo "❌ Terraform deployment failed!" + echo "Environment: ${{ github.event.inputs.environment }}" + echo "Region: ${{ github.event.inputs.region }}" + echo "Action: ${{ github.event.inputs.action }}" + exit 1 \ No newline at end of file diff --git a/INFRASTRUCTURE_SETUP.md b/INFRASTRUCTURE_SETUP.md new file mode 100644 index 0000000..f2a5b1d --- /dev/null +++ b/INFRASTRUCTURE_SETUP.md @@ -0,0 +1,260 @@ +# Infrastructure Setup with GitHub Actions and Terraform + +This project includes a complete infrastructure automation setup using Terraform and GitHub Actions for deploying to DigitalOcean. + +## 🚀 What's Included + +### 1. GitHub Actions Workflow +- **File**: `.github/workflows/terraform-digitalocean.yml` +- **Features**: + - Manual trigger with customizable parameters + - Support for multiple environments (dev, staging, prod) + - Support for all DigitalOcean regions + - Security scanning with Trivy + - Plan review and artifact upload + - Comprehensive logging and notifications + +### 2. Terraform Configuration +- **Main Configuration**: `terraform/main.tf` +- **DigitalOcean Resources**: `terraform/digitalocean.tf` +- **Features**: + - Multi-cloud provider support + - Environment-specific configurations + - Container registry and app platform + - Database clusters and load balancers + - Firewall and monitoring + - Custom domain support + +### 3. Setup Scripts +- **Setup Script**: `scripts/setup-github-actions.sh` +- **Features**: + - Automated GitHub secret configuration + - DigitalOcean token validation + - Workflow testing capabilities + - Interactive setup process + +### 4. Documentation +- **Workflow Documentation**: `.github/workflows/README.md` +- **Usage Examples**: `examples/workflow-examples.md` +- **Infrastructure Overview**: This document + +## 🏗️ Infrastructure Components + +### DigitalOcean Resources Created + +1. **Container Registry** + - Stores Docker images + - Basic tier subscription + - Region-specific deployment + +2. **App Platform** + - Containerized application hosting + - Auto-scaling capabilities + - Health checks and monitoring + - Environment-specific sizing + +3. **Database Cluster** (Production Only) + - PostgreSQL 15 + - Managed database service + - Automated backups + - Maintenance windows + +4. **Load Balancer** (Production Only) + - Traffic distribution + - Health checks + - SSL termination + +5. **Firewall** + - Network security rules + - HTTP/HTTPS access + - Application port access + - Outbound traffic rules + +6. **Spaces Bucket** + - Object storage for logs + - Lifecycle policies + - 30-day retention + +7. **Monitoring & Alerting** + - CPU utilization alerts + - Memory usage monitoring + - 5-minute windows + - 80% threshold + +8. **Domain & DNS** (Production Only) + - Custom domain support + - CNAME records + - SSL certificates + +## 🔧 Quick Start + +### Prerequisites +1. GitHub repository with Actions enabled +2. DigitalOcean account with API token +3. GitHub CLI (optional, for automated setup) + +### Step 1: Setup Secrets +```bash +# Run the automated setup script +./scripts/setup-github-actions.sh +``` + +Or manually: +1. Go to your GitHub repository → Settings → Secrets and variables → Actions +2. Add `DIGITALOCEAN_TOKEN` secret with your DigitalOcean API token + +### Step 2: Test the Workflow +1. Go to Actions tab in your GitHub repository +2. Select "Terraform DigitalOcean Infrastructure" +3. Click "Run workflow" +4. Choose parameters: + - Environment: `dev` + - Action: `plan` + - Region: `nyc1` + - Domain Name: (leave empty) + +### Step 3: Deploy Infrastructure +1. Review the plan output +2. Run workflow again with Action: `apply` +3. Monitor the deployment progress + +## 📋 Workflow Parameters + +| Parameter | Description | Options | Default | +|-----------|-------------|---------|---------| +| `environment` | Target environment | dev, staging, prod | dev | +| `action` | Terraform action | plan, apply, destroy | plan | +| `region` | DigitalOcean region | nyc1, sfo3, ams3, etc. | nyc1 | +| `domain_name` | Custom domain (optional) | Any valid domain | "" | + +## 🌍 Supported Regions + +- **US East**: `nyc1`, `nyc3` +- **US West**: `sfo2`, `sfo3` +- **Europe**: `ams2`, `ams3`, `fra1`, `lon1` +- **Asia**: `sgp1` +- **Canada**: `tor1` + +## 🔒 Security Features + +1. **Secret Management** + - API tokens stored in GitHub secrets + - No hardcoded credentials + +2. **Vulnerability Scanning** + - Trivy scanner integration + - SARIF output for GitHub Security tab + +3. **Network Security** + - Firewall rules for access control + - HTTPS-only production traffic + +4. **Environment Isolation** + - Separate configurations per environment + - Production-specific security measures + +## 💰 Cost Optimization + +### Development Environment +- **Estimated Cost**: $5-10/month +- **Resources**: 1 instance, basic sizing +- **Features**: Basic monitoring only + +### Staging Environment +- **Estimated Cost**: $20-40/month +- **Resources**: 2 instances, standard sizing +- **Features**: Full monitoring, optional domain + +### Production Environment +- **Estimated Cost**: $50-200/month +- **Resources**: 2+ instances, premium sizing +- **Features**: Full monitoring, custom domain, database, load balancer + +## 🚨 Best Practices + +### 1. Always Plan First +```bash +# Run plan before apply +gh workflow run terraform-digitalocean.yml -f action=plan -f environment=prod +# Review output, then apply +gh workflow run terraform-digitalocean.yml -f action=apply -f environment=prod +``` + +### 2. Use Environment-Specific Configurations +- Development: Minimal resources for cost savings +- Staging: Medium resources for testing +- Production: High availability with monitoring + +### 3. Monitor and Alert +- Set up DigitalOcean billing alerts +- Monitor resource usage +- Review security scan results + +### 4. Backup and Recovery +- Use managed database backups +- Consider cross-region replication +- Document recovery procedures + +## 🔧 Customization + +### Adding New Environments +1. Update the workflow parameters +2. Modify Terraform variables +3. Add environment-specific configurations + +### Adding New Resources +1. Update `terraform/digitalocean.tf` +2. Add new variables if needed +3. Test with plan action first + +### Customizing Monitoring +1. Modify alert thresholds +2. Add custom metrics +3. Configure notification channels + +## 🐛 Troubleshooting + +### Common Issues + +1. **Authentication Errors** + - Verify `DIGITALOCEAN_TOKEN` secret + - Check token permissions + +2. **Resource Limits** + - Check DigitalOcean account limits + - Verify sufficient credits + +3. **Region Issues** + - Ensure region is available + - Check resource availability + +4. **Terraform Errors** + - Review workflow logs + - Validate Terraform configuration + - Check variable values + +### Getting Help + +1. Check workflow logs in GitHub Actions +2. Review Terraform documentation +3. Consult DigitalOcean support +4. Open an issue in the repository + +## 📚 Additional Resources + +- [GitHub Actions Documentation](https://docs.github.com/en/actions) +- [Terraform Documentation](https://www.terraform.io/docs) +- [DigitalOcean API Documentation](https://docs.digitalocean.com/reference/api/) +- [DigitalOcean App Platform](https://docs.digitalocean.com/products/app-platform/) + +## 🤝 Contributing + +1. Fork the repository +2. Create a feature branch +3. Make your changes +4. Test with plan action +5. Submit a pull request + +## 📄 License + +This project is licensed under the MIT License - see the LICENSE file for details. \ No newline at end of file diff --git a/examples/workflow-examples.md b/examples/workflow-examples.md new file mode 100644 index 0000000..ef517af --- /dev/null +++ b/examples/workflow-examples.md @@ -0,0 +1,303 @@ +# GitHub Actions Workflow Examples + +This document provides examples of how to use the Terraform DigitalOcean Infrastructure workflow for different scenarios. + +## Basic Usage Examples + +### 1. Development Environment Setup + +**Scenario**: Setting up a development environment for testing + +**Parameters**: +- Environment: `dev` +- Action: `plan` +- Region: `nyc1` +- Domain Name: (empty) + +**Command**: +```bash +gh workflow run terraform-digitalocean.yml \ + -f environment=dev \ + -f action=plan \ + -f region=nyc1 \ + -f domain_name="" +``` + +**What it does**: +- Creates a Terraform plan for development infrastructure +- Uses minimal resources (1 instance, basic sizing) +- No custom domain or production features + +### 2. Production Environment Deployment + +**Scenario**: Deploying to production with custom domain + +**Parameters**: +- Environment: `prod` +- Action: `apply` +- Region: `sfo3` +- Domain Name: `myapp.example.com` + +**Command**: +```bash +gh workflow run terraform-digitalocean.yml \ + -f environment=prod \ + -f action=apply \ + -f region=sfo3 \ + -f domain_name="myapp.example.com" +``` + +**What it does**: +- Deploys production infrastructure with high availability +- Sets up custom domain and SSL certificates +- Enables monitoring and alerting +- Creates database cluster and load balancer + +### 3. Staging Environment Update + +**Scenario**: Updating staging environment with new configuration + +**Parameters**: +- Environment: `staging` +- Action: `plan` +- Region: `ams3` +- Domain Name: (empty) + +**Command**: +```bash +gh workflow run terraform-digitalocean.yml \ + -f environment=staging \ + -f action=plan \ + -f region=ams3 \ + -f domain_name="" +``` + +**What it does**: +- Shows what changes will be made to staging +- Allows review before applying +- Uses medium-sized resources + +### 4. Infrastructure Cleanup + +**Scenario**: Removing all infrastructure (use with caution!) + +**Parameters**: +- Environment: `dev` +- Action: `destroy` +- Region: `nyc1` +- Domain Name: (empty) + +**Command**: +```bash +gh workflow run terraform-digitalocean.yml \ + -f environment=dev \ + -f action=destroy \ + -f region=nyc1 \ + -f domain_name="" +``` + +**What it does**: +- Removes all DigitalOcean resources +- Deletes containers, databases, and storage +- **Warning**: This action cannot be undone! + +## Advanced Usage Examples + +### 5. Multi-Region Deployment + +**Scenario**: Deploying to multiple regions for global availability + +**Primary Region (US)**: +```bash +gh workflow run terraform-digitalocean.yml \ + -f environment=prod \ + -f action=apply \ + -f region=sfo3 \ + -f domain_name="us.myapp.example.com" +``` + +**Secondary Region (Europe)**: +```bash +gh workflow run terraform-digitalocean.yml \ + -f environment=prod \ + -f action=apply \ + -f region=ams3 \ + -f domain_name="eu.myapp.example.com" +``` + +### 6. Blue-Green Deployment + +**Scenario**: Zero-downtime deployment strategy + +**Step 1: Deploy to Green Environment**: +```bash +gh workflow run terraform-digitalocean.yml \ + -f environment=green \ + -f action=apply \ + -f region=nyc1 \ + -f domain_name="green.myapp.example.com" +``` + +**Step 2: Test Green Environment**: +- Verify the new deployment works correctly +- Run integration tests + +**Step 3: Switch Traffic**: +- Update DNS to point to green environment +- Monitor for any issues + +**Step 4: Cleanup Blue Environment**: +```bash +gh workflow run terraform-digitalocean.yml \ + -f environment=blue \ + -f action=destroy \ + -f region=nyc1 \ + -f domain_name="" +``` + +### 7. Disaster Recovery Setup + +**Scenario**: Setting up backup infrastructure in different region + +**Primary Infrastructure**: +```bash +gh workflow run terraform-digitalocean.yml \ + -f environment=prod \ + -f action=apply \ + -f region=sfo3 \ + -f domain_name="myapp.example.com" +``` + +**Disaster Recovery Infrastructure**: +```bash +gh workflow run terraform-digitalocean.yml \ + -f environment=dr \ + -f action=apply \ + -f region=lon1 \ + -f domain_name="dr.myapp.example.com" +``` + +## Environment-Specific Configurations + +### Development Environment +- **Resources**: Minimal (1 instance, basic sizing) +- **Features**: Basic monitoring, no custom domain +- **Cost**: ~$5-10/month +- **Use Case**: Development and testing + +### Staging Environment +- **Resources**: Medium (2 instances, standard sizing) +- **Features**: Full monitoring, optional custom domain +- **Cost**: ~$20-40/month +- **Use Case**: Pre-production testing + +### Production Environment +- **Resources**: High availability (2+ instances, premium sizing) +- **Features**: Full monitoring, custom domain, SSL, database cluster +- **Cost**: ~$50-200/month +- **Use Case**: Live production workloads + +## Best Practices + +### 1. Always Plan First +```bash +# Always run plan before apply +gh workflow run terraform-digitalocean.yml -f action=plan -f environment=prod +# Review the plan output +# Then run apply +gh workflow run terraform-digitalocean.yml -f action=apply -f environment=prod +``` + +### 2. Use Descriptive Environment Names +```bash +# Good: Clear environment names +gh workflow run terraform-digitalocean.yml -f environment=prod-us-east +gh workflow run terraform-digitalocean.yml -f environment=staging-eu + +# Avoid: Generic names +gh workflow run terraform-digitalocean.yml -f environment=env1 +``` + +### 3. Monitor Costs +- Set up billing alerts in DigitalOcean +- Use appropriate instance sizes for each environment +- Clean up unused resources regularly + +### 4. Security Considerations +- Use different API tokens for different environments +- Enable security scanning in the workflow +- Review Terraform plans for security implications + +## Troubleshooting Examples + +### Common Issues and Solutions + +**1. Authentication Error**: +``` +Error: DigitalOcean API token is invalid +``` +**Solution**: Verify your `DIGITALOCEAN_TOKEN` secret is correctly set + +**2. Resource Limit Exceeded**: +``` +Error: Droplet limit exceeded +``` +**Solution**: Check your DigitalOcean account limits or upgrade your plan + +**3. Region Unavailable**: +``` +Error: Region not available +``` +**Solution**: Choose a different DigitalOcean region from the supported list + +**4. Domain Already Exists**: +``` +Error: Domain already exists +``` +**Solution**: Use a unique domain name or remove the existing domain first + +## Integration Examples + +### With CI/CD Pipeline +```yaml +# In your main CI/CD workflow +- name: Deploy to Staging + run: | + gh workflow run terraform-digitalocean.yml \ + -f environment=staging \ + -f action=apply \ + -f region=nyc1 + if: github.ref == 'refs/heads/develop' + +- name: Deploy to Production + run: | + gh workflow run terraform-digitalocean.yml \ + -f environment=prod \ + -f action=apply \ + -f region=sfo3 \ + -f domain_name="myapp.example.com" + if: github.ref == 'refs/heads/main' +``` + +### With Slack Notifications +```yaml +# Add to your workflow +- name: Notify Slack + uses: 8398a7/action-slack@v3 + with: + status: ${{ job.status }} + channel: '#deployments' + text: 'Terraform deployment ${{ github.event.inputs.action }} to ${{ github.event.inputs.environment }}' + if: always() +``` + +### With Jira Integration +```yaml +# Add to your workflow +- name: Update Jira + uses: atlassian/gajira-transition@v3 + with: + issue: ${{ github.event.inputs.jira_issue }} + transition: 'Deploy' + if: success() +``` \ No newline at end of file diff --git a/scripts/setup-github-actions.sh b/scripts/setup-github-actions.sh new file mode 100755 index 0000000..59bb9e5 --- /dev/null +++ b/scripts/setup-github-actions.sh @@ -0,0 +1,193 @@ +#!/bin/bash + +# GitHub Actions Setup Script for Terraform DigitalOcean Infrastructure +# This script helps you set up the required secrets and test the workflow + +set -e + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# Function to print colored output +print_status() { + echo -e "${BLUE}[INFO]${NC} $1" +} + +print_success() { + echo -e "${GREEN}[SUCCESS]${NC} $1" +} + +print_warning() { + echo -e "${YELLOW}[WARNING]${NC} $1" +} + +print_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +# Check if required tools are installed +check_requirements() { + print_status "Checking requirements..." + + if ! command -v gh &> /dev/null; then + print_error "GitHub CLI (gh) is not installed. Please install it first:" + echo " https://cli.github.com/" + exit 1 + fi + + if ! command -v terraform &> /dev/null; then + print_warning "Terraform is not installed. It will be installed by the workflow." + fi + + print_success "Requirements check completed" +} + +# Check if user is authenticated with GitHub CLI +check_github_auth() { + print_status "Checking GitHub authentication..." + + if ! gh auth status &> /dev/null; then + print_error "You are not authenticated with GitHub CLI. Please run:" + echo " gh auth login" + exit 1 + fi + + print_success "GitHub authentication verified" +} + +# Get repository information +get_repo_info() { + print_status "Getting repository information..." + + # Get current repository + REPO=$(gh repo view --json nameWithOwner -q .nameWithOwner) + if [ -z "$REPO" ]; then + print_error "Could not determine repository. Make sure you're in a git repository." + exit 1 + fi + + print_success "Repository: $REPO" +} + +# Check if secrets already exist +check_existing_secrets() { + print_status "Checking existing secrets..." + + if gh secret list 2>/dev/null | grep -q "DIGITALOCEAN_TOKEN"; then + print_warning "DIGITALOCEAN_TOKEN secret already exists" + read -p "Do you want to update it? (y/N): " -n 1 -r + echo + if [[ ! $REPLY =~ ^[Yy]$ ]]; then + print_status "Skipping secret setup" + return 0 + fi + fi +} + +# Setup DigitalOcean token +setup_digitalocean_token() { + print_status "Setting up DigitalOcean API token..." + + echo "To get your DigitalOcean API token:" + echo "1. Go to https://cloud.digitalocean.com/account/api/tokens" + echo "2. Click 'Generate New Token'" + echo "3. Give it a name (e.g., 'GitHub Actions Terraform')" + echo "4. Select 'Write' scope" + echo "5. Copy the token" + echo + + read -p "Enter your DigitalOcean API token: " -s DO_TOKEN + echo + + if [ -z "$DO_TOKEN" ]; then + print_error "Token cannot be empty" + exit 1 + fi + + # Test the token + print_status "Testing DigitalOcean token..." + if curl -s -H "Authorization: Bearer $DO_TOKEN" https://api.digitalocean.com/v2/account | grep -q "account"; then + print_success "DigitalOcean token is valid" + else + print_error "Invalid DigitalOcean token. Please check your token and try again." + exit 1 + fi + + # Set the secret + print_status "Setting GitHub secret..." + echo "$DO_TOKEN" | gh secret set DIGITALOCEAN_TOKEN + + print_success "DigitalOcean token secret has been set" +} + +# Test the workflow +test_workflow() { + print_status "Testing workflow..." + + echo "The workflow will be triggered manually. You can:" + echo "1. Go to https://github.com/$REPO/actions" + echo "2. Select 'Terraform DigitalOcean Infrastructure'" + echo "3. Click 'Run workflow'" + echo "4. Choose parameters:" + echo " - Environment: dev" + echo " - Action: plan" + echo " - Region: nyc1" + echo " - Domain Name: (leave empty)" + echo + + read -p "Do you want to trigger a test workflow now? (y/N): " -n 1 -r + echo + if [[ $REPLY =~ ^[Yy]$ ]]; then + print_status "Triggering test workflow..." + gh workflow run terraform-digitalocean.yml \ + -f environment=dev \ + -f action=plan \ + -f region=nyc1 \ + -f domain_name="" + + print_success "Workflow triggered! Check the Actions tab to monitor progress." + fi +} + +# Show next steps +show_next_steps() { + echo + print_success "Setup completed successfully!" + echo + echo "Next steps:" + echo "1. Monitor your first workflow run in the Actions tab" + echo "2. Review the Terraform plan before applying" + echo "3. For production deployments, consider:" + echo " - Setting up remote state storage" + echo " - Configuring domain names" + echo " - Setting up monitoring and alerting" + echo "4. Review the workflow documentation at .github/workflows/README.md" + echo + echo "Useful commands:" + echo " gh workflow list # List all workflows" + echo " gh workflow run terraform-digitalocean.yml # Trigger workflow" + echo " gh secret list # List secrets" + echo +} + +# Main execution +main() { + echo "GitHub Actions Setup for Terraform DigitalOcean Infrastructure" + echo "==============================================================" + echo + + check_requirements + check_github_auth + get_repo_info + check_existing_secrets + setup_digitalocean_token + test_workflow + show_next_steps +} + +# Run main function +main "$@" \ No newline at end of file