GitLab CI/CD · Setup Guide

AMR WhatsApp CRM — Deploy Automático

AUD-20260925-007 Volver
FOLIO: AUD-20260925-007 Secuencia: Auditoría #007 del día 2026-09-25
📅 2026-09-25 — COT 👤 Auditor: Anderson Mares (AMR TECH) ● VIGENTE

GitLab CI/CD

SETUP COMPLETO PASO A PASO

Plan de implementación completo para conectar el repositorio GitHub de AMR CRM a GitLab CI/CD. Incluye configuración de variables, deploy automático a staging y producción, y monitoreo de pipelines.

GitHub: anderman1981/amrstreaming Hostinger: 151.106.96.98:65002 Branches: main → prod, dev → staging

Arquitectura del Pipeline

💻
Push Local
git push origin main
🔍
Validate
PHP Lint check
🚀
Deploy Staging
rsync → /staging/
🧪
Smoke Test
HTTP 401/503 check
✅
Deploy Prod
Manual gate → /main/
🔔
Notify
Webhook → WhatsApp

Mirror strategy: El código vive en GitHub. GitLab actúa como CI runner — hace mirror del repo y ejecuta el pipeline. No necesitas migrar el código.

1

Crear cuenta GitLab & proyecto

Configuración inicial de la plataforma CI/CD

1.1
Ve a https://gitlab.com y crea una cuenta gratuita (o inicia sesión si ya tienes).
1.2
Clic en New project → Create blank project.
Nombre: amrstreaming-crm · Visibility: Private · NO inicializar con README.
1.3
En tu proyecto GitLab ve a Settings → Repository → Mirroring repositories.
Agrega el mirror de GitHub:
URL: https://github.com/anderman1981/amrstreaming.git
Direction: Pull (GitLab pulls from GitHub)
Mirror branches: All
Necesitarás un GitHub Personal Access Token con permisos repo. Créalo en github.com → Settings → Developer settings → Personal access tokens → Tokens (classic).

Alternativa más simple: Puedes empujar directamente a GitLab agregando un segundo remote:
git remote add gitlab https://gitlab.com/TU_USER/amrstreaming-crm.git
Luego cada push: git push github && git push gitlab

2

Generar clave SSH para el deploy

El runner de GitLab necesita conectarse a Hostinger via SSH

2.1
En tu Mac local, genera un par de claves SSH dedicado para el CI:
ssh-keygen -t ed25519 -C "gitlab-ci-amrcrm" -f ~/.ssh/gitlab_ci_amrcrm -N ""
Esto crea ~/.ssh/gitlab_ci_amrcrm (privada) y ~/.ssh/gitlab_ci_amrcrm.pub (pública).
2.2
Copia la clave pública al servidor Hostinger:
# Primero muestra la clave pública:
cat ~/.ssh/gitlab_ci_amrcrm.pub

# Luego conéctate al servidor y agrégala:
ssh -p 65002 u305025526@151.106.96.98
echo "PEGA_AQUI_LA_CLAVE_PUBLICA" >> ~/.ssh/authorized_keys
2.3
Obtén el fingerprint del servidor para el host key:
ssh-keyscan -p 65002 -H 151.106.96.98
Copia el output completo — lo necesitas en el siguiente paso.
3

Configurar Variables CI/CD en GitLab

Settings → CI/CD → Variables

Ve a tu proyecto GitLab → Settings → CI/CD → Variables → Expand → Add variable para cada una:

Variable Tipo Valor Notas
SSH_PRIVATE_KEY File Contenido de ~/.ssh/gitlab_ci_amrcrm Incluye las líneas -----BEGIN/END-----
SSH_HOST_KEY Variable Output del ssh-keyscan del paso 2.3 Previene MITM attacks
WEBHOOK_DEPLOY_TOKEN Variable Token de tu .env en producción Para notificación post-deploy

IMPORTANTE: Para SSH_PRIVATE_KEY usa tipo File, no Variable. El runner la monta como archivo en el runner job. Marca "Protect variable" para que solo se use en ramas protegidas.

4

El archivo .gitlab-ci.yml ya está listo

Ya fue commiteado en el repo — .gitlab-ci.yml

El pipeline ya existe en el repo (commit f5705f7). Resumen de lo que hace:

php-lint rama: main, dev, staging

Valida sintaxis PHP de todos los archivos src/ y public/. Falla el pipeline antes de cualquier deploy si hay error de PHP.

deploy-staging rama: dev

rsync a /whatsapp-crm/staging/. Excluye .env, .git, node_modules, *.log.

test-staging rama: dev

Smoke test: verifica que webhook responde HTTP 401 o 503 (comportamiento correcto sin token). Bloquea el pipeline si responde 200 o 500.

deploy-production rama: main — MANUAL GATE

rsync a /whatsapp-crm/main/. Requiere click manual en GitLab UI para disparar. Nunca se auto-deploya a producción.

# Resumen del pipeline (ya en .gitlab-ci.yml):
stages:
  - validate        # php -l en todos los archivos
  - deploy-staging  # rsync a staging (rama dev)
  - test-staging    # smoke test webhook
  - deploy-production # rsync a prod (rama main, manual)
  - notify          # webhook post-deploy
5

Hacer el primer push a GitLab

Conectar el repositorio local con GitLab y lanzar el primer pipeline

5.1
Agrega GitLab como segundo remote:
# Reemplaza TU_USER con tu usuario de GitLab
git remote add gitlab https://gitlab.com/TU_USER/amrstreaming-crm.git

# Verifica los remotes:
git remote -v
5.2
Push inicial a GitLab (todos los branches):
git push gitlab --all
git push gitlab --tags
5.3
Abre GitLab → tu proyecto → CI/CD → Pipelines. Deberías ver el primer pipeline corriendo. El stage php-lint debe pasar en verde.
5.4
Para el workflow de trabajo habitual, usa un alias o script:
# Alias para push a ambos remotes (agrega a ~/.zshrc):
alias gpush='git push origin && git push gitlab'

# O un script en el repo:
# scripts/push-all.sh
#!/bin/bash
git push origin "$@"
git push gitlab "$@"
6

Workflow de trabajo con CI/CD activo

Cómo trabajar con el pipeline en el día a día

Desarrollo normal

# 1. Crea branch de feature
git checkout -b feature/mi-mejora

# 2. Haz cambios, commitea
git add .
git commit -m "feat: descripcion"

# 3. Push a dev para CI
git push origin feature/mi-mejora
git push gitlab feature/mi-mejora

# 4. Merge a dev → staging auto-deploy
git checkout dev
git merge feature/mi-mejora
gpush  # push a ambos remotes

Deploy a producción

# 1. Merge dev → main
git checkout main
git merge dev
gpush  # push a ambos remotes

# 2. GitLab corre php-lint

# 3. Ve a GitLab → Pipelines
# Busca el pipeline de main
# Clic "▶ Play" en deploy-production

# 4. Verifica en producción:
curl https://streamingapps.online/\
  whatsapp-crm/main/public/webhook.php
# Debe responder 401 o 503
7

Instalar Backups y Monitoreo en Hostinger

Comandos a ejecutar UNA vez desde tu servidor

Pendiente crítico: Estos scripts ya fueron subidos al servidor pero los crons aún no están instalados. Ejecuta los siguientes comandos en Hostinger para activarlos.

7.1 Conectar al servidor:

ssh -p 65002 -i ~/.ssh/id_ed25519_amrosai u305025526@151.106.96.98

7.2 Instalar crons de backup + monitoreo:

bash ~/scripts/monitor-setup.sh

Esto instala: backup DB a las 3:00 AM diario + health check cada 5 minutos.

7.3 Verificar crons instalados:

crontab -l

Debes ver las líneas de backup-hostinger y health-check.

7.4 Limpiar archivos basura del servidor:

ls ~/domains/streamingapps.online/public_html/
# Eliminar solo si ves estos archivos:
rm ~/domains/streamingapps.online/public_html/tmp_batch.php
rm ~/domains/streamingapps.online/public_html/tmp_update_sales.php
rm ~/domains/streamingapps.online/public_html/fix_payment_security_20260923.php
8

CRÍTICO: Actualizar .env de Producción

El CRM retorna 503 hasta que estos valores estén configurados

Bloqueante MVP: auth.php ahora requiere CRM_PASSWORD en producción. Hasta que lo configures, el admin CRM devuelve HTTP 503 a todos los usuarios.

Editar .env en el servidor:

# Conectar al servidor:
ssh -p 65002 -i ~/.ssh/id_ed25519_amrosai u305025526@151.106.96.98

# Editar .env de producción:
nano ~/domains/streamingapps.online/public_html/whatsapp-crm/main/.env

# Agregar / actualizar estas líneas:
CRM_PASSWORD=pon_una_contrasena_segura_aqui
INSTALL_SECRET=secreto_para_install_php_32chars

Genera contraseñas seguras:
openssl rand -base64 32 — ejecuta en tu terminal local para generar valores seguros.

9

Ejecutar Migración SQL en Producción

migration_002_mvp_fixes.sql — agrega columnas faltantes

La migración agrega: web_leads table, columnas manual_takeover, columnas ai_profiles, índices de performance. Sin esto el CRM puede crashear en el primer nuevo contacto.

# En el servidor, cargar variables del .env:
source <(grep -E '^(DB_HOST|DB_NAME|DB_USER|DB_PASS)=' \
  ~/domains/streamingapps.online/public_html/whatsapp-crm/main/.env \
  | sed 's/^/export /')

# Ejecutar migración:
mysql -h"$DB_HOST" -u"$DB_USER" -p"$DB_PASS" "$DB_NAME" \
  < ~/domains/streamingapps.online/public_html/whatsapp-crm/main/db/migration_002_mvp_fixes.sql

# Verificar:
echo "SELECT table_name FROM information_schema.tables WHERE table_name='web_leads';" \
  | mysql -h"$DB_HOST" -u"$DB_USER" -p"$DB_PASS" "$DB_NAME"

Checklist Completo — MVP Launch

Semana 1 Post-Launch

Días 1-2
  • • Monitorear logs del servidor
  • • Verificar backups creándose
  • • Probar flujo completo WhatsApp
Días 3-4
  • • CSRF tokens en formularios
  • • Índice messages.wamid
  • • Rate limiting en login
Días 5-7
  • • Fix mobile layout CRM
  • • Barra de búsqueda funcional
  • • Primer cliente real en CRM