Some checks failed
CI/CD - Francia Ocupada (La Resistencia) / build-and-deploy (push) Failing after 7s
234 lines
7.3 KiB
Markdown
234 lines
7.3 KiB
Markdown
# 🔧 Troubleshooting CI/CD - Problemas Resueltos
|
|
|
|
## Resumen de Problemas Encontrados y Soluciones
|
|
|
|
Durante la configuración del CI/CD con Gitea Actions, encontramos varios problemas que fueron resueltos paso a paso. Este documento sirve como referencia para futuros problemas similares.
|
|
|
|
---
|
|
|
|
## Problema 1: Error en el Checkout - Variables de Contexto
|
|
|
|
### ❌ Error
|
|
```
|
|
%!t(string=http://gitea.local:3000)
|
|
%!t(string=***)
|
|
%!t(string=marti/FranciaOcupada)
|
|
```
|
|
|
|
### 🔍 Causa
|
|
El workflow intentaba usar variables de contexto de Gitea (`${{ gitea.server_url }}`, `${{ gitea.repository }}`, `${{ gitea.token }}`) en el paso de checkout, pero estas no se interpolaban correctamente.
|
|
|
|
### ✅ Solución
|
|
Simplificar el checkout eliminando los parámetros innecesarios:
|
|
|
|
```yaml
|
|
# ❌ ANTES (No funcionaba)
|
|
- name: 🚀 Checkout del Código
|
|
uses: actions/checkout@v4
|
|
with:
|
|
server-url: ${{ gitea.server_url }}
|
|
repository: ${{ gitea.repository }}
|
|
token: ${{ gitea.token }}
|
|
fetch-depth: 0
|
|
|
|
# ✅ DESPUÉS (Funciona)
|
|
- name: 🚀 Checkout del Código
|
|
uses: actions/checkout@v4
|
|
with:
|
|
fetch-depth: 0
|
|
```
|
|
|
|
**Commit**: `609033b` - "fix: Corregir checkout en workflow de Gitea Actions"
|
|
|
|
---
|
|
|
|
## Problema 2: Node.js No Encontrado
|
|
|
|
### ❌ Error
|
|
```
|
|
Cannot find: node in PATH
|
|
```
|
|
|
|
### 🔍 Causa
|
|
El runner de Gitea Actions no tiene Node.js preinstalado, y las acciones de GitHub (como `actions/checkout@v4` y `actions/setup-node@v4`) requieren Node.js para ejecutarse.
|
|
|
|
### ✅ Solución
|
|
Instalar Node.js manualmente usando comandos del sistema ANTES de cualquier acción de GitHub:
|
|
|
|
```yaml
|
|
- name: 📦 Instalar Node.js
|
|
shell: bash
|
|
run: |
|
|
echo "Verificando si Node.js está instalado..."
|
|
if ! command -v node &> /dev/null; then
|
|
echo "Node.js no encontrado, instalando..."
|
|
|
|
# Detectar el sistema operativo
|
|
if [ -f /etc/debian_version ]; then
|
|
# Debian/Ubuntu
|
|
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
|
apt-get install -y nodejs
|
|
elif [ -f /etc/redhat-release ]; then
|
|
# RedHat/CentOS/Fedora
|
|
curl -fsSL https://rpm.nodesource.com/setup_20.x | bash -
|
|
yum install -y nodejs
|
|
elif [ -f /etc/alpine-release ]; then
|
|
# Alpine Linux
|
|
apk add --no-cache nodejs npm
|
|
else
|
|
# Fallback a nvm
|
|
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
|
|
export NVM_DIR="$HOME/.nvm"
|
|
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
|
|
nvm install 20
|
|
fi
|
|
else
|
|
echo "Node.js ya está instalado: $(node --version)"
|
|
fi
|
|
|
|
# Verificar instalación
|
|
node --version
|
|
npm --version
|
|
```
|
|
|
|
**Commit**: `7c9ff53` - "feat: Instalación manual de Node.js en el runner"
|
|
|
|
---
|
|
|
|
## Problema 3: Scripts No Encontrados (2.sh, 3.sh, 4.sh)
|
|
|
|
### ❌ Error
|
|
```
|
|
/root/.cache/act/6d07dd4849690bae/act/workflow/2.sh: line 3: docker: command not found
|
|
/root/.cache/act/6d07dd4849690bae/act/workflow/3.sh: line 3: docker: command not found
|
|
/root/.cache/act/6d07dd4849690bae/act/workflow/4.sh: line 3: docker: command not found
|
|
```
|
|
|
|
### 🔍 Causa
|
|
El runner de Gitea Actions (basado en `act`) estaba creando archivos temporales (2.sh, 3.sh, 4.sh) para ejecutar los bloques `run:`, pero no especificaba correctamente el shell a usar, causando que los comandos no se ejecutaran en el contexto correcto.
|
|
|
|
### ✅ Solución
|
|
Especificar explícitamente `shell: bash` en todos los pasos que usan bloques `run:`:
|
|
|
|
```yaml
|
|
# ❌ ANTES (No funcionaba)
|
|
- name: 🛑 Detener Contenedores Anteriores
|
|
run: |
|
|
echo "Deteniendo contenedores existentes..."
|
|
docker compose -f docker-compose_prod.yml down || true
|
|
|
|
# ✅ DESPUÉS (Funciona)
|
|
- name: 🛑 Detener Contenedores Anteriores
|
|
shell: bash
|
|
run: |
|
|
echo "Deteniendo contenedores existentes..."
|
|
docker compose -f docker-compose_prod.yml down || true
|
|
```
|
|
|
|
**Commit**: `134460a` - "fix: Especificar shell bash explícitamente en todos los pasos"
|
|
|
|
---
|
|
|
|
## Orden Correcto de los Pasos
|
|
|
|
El orden final correcto de los pasos es:
|
|
|
|
1. **Instalar Node.js** (con `shell: bash`)
|
|
2. **Checkout del Código** (usando `actions/checkout@v4`)
|
|
3. **Detener Contenedores Anteriores** (con `shell: bash`)
|
|
4. **Limpiar Imágenes Antiguas** (con `shell: bash`)
|
|
5. **Construir Imágenes Docker** (con `shell: bash`)
|
|
6. **Desplegar Aplicación** (con `shell: bash`)
|
|
7. **Verificar Despliegue** (con `shell: bash`)
|
|
8. **Mostrar Logs Recientes** (con `shell: bash` e `if: always()`)
|
|
|
|
---
|
|
|
|
## Lecciones Aprendidas
|
|
|
|
### 1. Diferencias entre GitHub Actions y Gitea Actions
|
|
- Gitea Actions usa `act` bajo el capó, que tiene algunas diferencias con GitHub Actions
|
|
- No todas las variables de contexto funcionan igual
|
|
- El runner puede no tener las mismas herramientas preinstaladas
|
|
|
|
### 2. Especificar el Shell es Importante
|
|
- Siempre especifica `shell: bash` cuando uses bloques `run:` con múltiples líneas
|
|
- Esto evita problemas de interpretación de comandos
|
|
|
|
### 3. Node.js es Requerido
|
|
- Muchas acciones de GitHub requieren Node.js
|
|
- En runners de Gitea, puede que necesites instalarlo manualmente
|
|
- Instálalo ANTES de usar cualquier acción de GitHub
|
|
|
|
### 4. El Runner Necesita Acceso a Docker
|
|
- Asegúrate de que el runner tenga acceso al socket de Docker del host
|
|
- En tu configuración: `-v /var/run/docker.sock:/var/run/docker.sock`
|
|
- La etiqueta debe ser `production-ready:host` para acceso al Docker del host
|
|
|
|
---
|
|
|
|
## Configuración del Runner
|
|
|
|
Tu configuración del runner que funciona:
|
|
|
|
```yaml
|
|
services:
|
|
gitea-runner:
|
|
image: gitea/act_runner:latest
|
|
container_name: gitea-act_runner
|
|
restart: always
|
|
volumes:
|
|
- /var/run/docker.sock:/var/run/docker.sock
|
|
environment:
|
|
- GITEA_INSTANCE_URL=http://gitea.local:3000
|
|
- GITEA_RUNNER_NAME=runner-01-ci-vm
|
|
- GITEA_RUNNER_LABELS=production-ready:host
|
|
- GITEA_RUNNER_REGISTRATION_TOKEN=jzLi65hxB1Rt2RgIGFglXB5RjW9ggCbq9UFX3NrS
|
|
```
|
|
|
|
**Puntos clave**:
|
|
- `production-ready:host` - La etiqueta `:host` es crucial para acceso a Docker
|
|
- Volumen del socket de Docker montado
|
|
- URL de Gitea correcta
|
|
|
|
---
|
|
|
|
## Verificación Post-Despliegue
|
|
|
|
Después de un despliegue exitoso, verifica:
|
|
|
|
```bash
|
|
# 1. Estado de contenedores
|
|
docker compose -f docker-compose_prod.yml ps
|
|
|
|
# 2. Logs recientes
|
|
docker compose -f docker-compose_prod.yml logs --tail=50
|
|
|
|
# 3. Acceso a la aplicación
|
|
curl -I https://franciaocupada.martivich.es
|
|
curl -I https://api.franciaocupada.martivich.es
|
|
|
|
# 4. Estado del runner
|
|
docker ps | grep gitea-act_runner
|
|
```
|
|
|
|
---
|
|
|
|
## Recursos Útiles
|
|
|
|
- **Gitea Actions Docs**: https://docs.gitea.com/usage/actions/overview
|
|
- **Act Runner**: https://gitea.com/gitea/act_runner
|
|
- **GitHub Actions Syntax**: https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions
|
|
|
|
---
|
|
|
|
## Próximas Mejoras Recomendadas
|
|
|
|
1. **Caché de Node.js**: Cachear la instalación de Node.js para acelerar futuros builds
|
|
2. **Tests Automatizados**: Agregar tests antes del deploy
|
|
3. **Rollback Automático**: Implementar rollback si el deploy falla
|
|
4. **Notificaciones**: Configurar notificaciones de éxito/fallo (email, Discord, etc.)
|
|
5. **Health Checks**: Verificar que la app responde correctamente antes de dar por exitoso el deploy
|
|
6. **Backup de DB**: Hacer backup de la base de datos antes de cada deploy
|
|
7. **Staging Environment**: Crear un ambiente de staging para probar antes de producción
|