name: CD on: push: branches: [main] env: REGISTRY: ghcr.io IMAGE_NAME: ${{ github.repository }} jobs: # ── 1. Tests deben pasar antes de buildear ────────────────────────────── test: name: Tests (gate) runs-on: ubuntu-latest env: DATABASE_URL: sqlite:///./test.db JWT_SECRET: ci-test-secret-key-not-used-in-production-32chars ENVIRONMENT: development MOCK_EXTERNAL_SERVICES: "true" steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: "3.12" cache: pip - run: pip install -r requirements-dev.txt - run: pytest tests/ -v # ── 2. Build y push de la imagen Docker a ghcr.io ────────────────────── build-and-push: name: Build & Push Docker needs: test runs-on: ubuntu-latest permissions: contents: read packages: write outputs: image-tag: ${{ steps.meta.outputs.tags }} image-digest: ${{ steps.build.outputs.digest }} steps: - uses: actions/checkout@v4 - name: Log in to GitHub Container Registry uses: docker/login-action@v3 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Extract Docker metadata id: meta uses: docker/metadata-action@v5 with: images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} tags: | type=sha,prefix=sha- type=raw,value=latest,enable=true - name: Build and push image id: build uses: docker/build-push-action@v6 with: context: . push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} cache-from: type=gha cache-to: type=gha,mode=max # ── 3. Deploy al servidor de producción (requiere secrets configurados) ─ # # Para activar este job: # 1. Ir a GitHub → Settings → Variables → New repository variable # DEPLOY_ENABLED = true # 2. Agregar los siguientes Secrets (Settings → Secrets): # DEPLOY_HOST — IP o dominio del servidor # DEPLOY_USER — usuario SSH (ej: ubuntu, deploy) # DEPLOY_KEY — clave privada SSH (contenido del archivo .pem / id_rsa) # 3. En el servidor tener docker + docker compose y el archivo .env en # /opt/m6-backend/.env con las variables de producción deploy: name: Deploy to Production needs: build-and-push runs-on: ubuntu-latest environment: production if: ${{ vars.DEPLOY_ENABLED == 'true' }} steps: - name: Deploy via SSH uses: appleboy/ssh-action@v1.2.0 with: host: ${{ secrets.DEPLOY_HOST }} username: ${{ secrets.DEPLOY_USER }} key: ${{ secrets.DEPLOY_KEY }} script: | set -e cd /opt/m6-backend # Autenticar en ghcr.io dentro del servidor echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io \ -u ${{ github.actor }} --password-stdin # Bajar imagen nueva y levantar sin downtime docker compose pull backend docker compose up -d --no-build --remove-orphans # Limpiar imágenes viejas docker image prune -f echo "Deploy completado: $(date)"