CI/CD con Nexus¶
Integra Nexus en tu pipeline de CI/CD para automatizar despliegues inteligentes.
Objetivo¶
Al final de esta guía tendrás:
- ✅ Despliegue automático cuando hay cambios en Git
- ✅ Validación pre-deploy con IA
- ✅ Notificaciones en cada paso
- ✅ Rollback automático si hay problemas
Prerrequisitos¶
- Repositorio en GitHub/GitLab
- Pipeline de CI/CD existente (GitHub Actions, Jenkins, etc.)
- API Key de Nexus
Arquitectura¶
graph LR
A[Push a Git] --> B[CI/CD Pipeline]
B --> C[Tests]
C --> D[Nexus: Validación IA]
D --> E{Aprobado?}
E -->|Sí| F[Deploy]
E -->|No| G[Notificar]
F --> H[Nexus: Health Check]
H --> I{OK?}
I -->|Sí| J[Éxito]
I -->|No| K[Rollback]
Paso 1: Crea API Key¶
- Ve a Mi cuenta > API Keys
- Crea una nueva key con permisos:
- Tareas: Ejecución
- Ejecuciones: Lectura
- Guarda la key de forma segura
Paso 2: Crea las tareas en Nexus¶
Tarea: Validación pre-deploy¶
Prompt:
Analiza los cambios de código propuestos para deploy.
## Datos de entrada:
- Commit: ${COMMIT_SHA}
- Branch: ${BRANCH}
- Cambios: ${CHANGED_FILES}
- PR Description: ${PR_DESCRIPTION}
## Validaciones a realizar:
1. **Seguridad**
- Busca credenciales hardcodeadas
- Detecta vulnerabilidades conocidas
- Verifica dependencias
2. **Calidad**
- Revisa patrones de código
- Identifica code smells
- Verifica cobertura de tests
3. **Riesgo**
- Evalúa impacto de los cambios
- Identifica cambios en BD
- Detecta breaking changes
## Output esperado:
- approved: true/false
- risk_level: low/medium/high
- findings: lista de hallazgos
- recommendations: sugerencias
Tarea: Health check post-deploy¶
Prompt:
Verifica que el despliegue fue exitoso.
## Verificaciones:
1. Endpoints críticos responden
2. No hay errores en logs
3. Métricas están normales
4. Base de datos accesible
## URLs a verificar:
- ${APP_URL}/health
- ${APP_URL}/api/status
- ${APP_URL}/
## Resultado esperado:
- healthy: true/false
- issues: lista de problemas
- metrics: métricas relevantes
Paso 3: Integra con GitHub Actions¶
Crea .github/workflows/deploy.yml:
name: Deploy with Nexus Validation
on:
push:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run tests
run: npm test
validate:
needs: test
runs-on: ubuntu-latest
steps:
- name: Validate with Nexus
id: nexus-validate
run: |
RESPONSE=$(curl -X POST \
"https://api.nexus.app/v1/tasks/validate-deployment/execute" \
-H "Authorization: Bearer ${{ secrets.NEXUS_API_KEY }}" \
-H "Content-Type: application/json" \
-d '{
"parameters": {
"COMMIT_SHA": "${{ github.sha }}",
"BRANCH": "${{ github.ref_name }}",
"CHANGED_FILES": "${{ steps.changes.outputs.files }}",
"PR_DESCRIPTION": "${{ github.event.pull_request.body }}"
}
}')
APPROVED=$(echo $RESPONSE | jq -r '.result.approved')
echo "approved=$APPROVED" >> $GITHUB_OUTPUT
if [ "$APPROVED" != "true" ]; then
echo "Deployment not approved by Nexus"
echo $RESPONSE | jq '.result.findings'
exit 1
fi
deploy:
needs: validate
runs-on: ubuntu-latest
steps:
- name: Deploy to production
run: |
# Tu comando de deploy
./deploy.sh production
- name: Health check with Nexus
run: |
RESPONSE=$(curl -X POST \
"https://api.nexus.app/v1/tasks/post-deploy-health/execute" \
-H "Authorization: Bearer ${{ secrets.NEXUS_API_KEY }}" \
-H "Content-Type: application/json" \
-d '{
"parameters": {
"APP_URL": "https://app.miempresa.com"
}
}')
HEALTHY=$(echo $RESPONSE | jq -r '.result.healthy')
if [ "$HEALTHY" != "true" ]; then
echo "Health check failed, initiating rollback"
./rollback.sh
exit 1
fi
Paso 4: Integra con Jenkins¶
pipeline {
agent any
environment {
NEXUS_API_KEY = credentials('nexus-api-key')
}
stages {
stage('Test') {
steps {
sh 'npm test'
}
}
stage('Nexus Validation') {
steps {
script {
def response = httpRequest(
url: 'https://api.nexus.app/v1/tasks/validate-deployment/execute',
httpMode: 'POST',
customHeaders: [[name: 'Authorization', value: "Bearer ${NEXUS_API_KEY}"]],
contentType: 'APPLICATION_JSON',
requestBody: """{
"parameters": {
"COMMIT_SHA": "${env.GIT_COMMIT}",
"BRANCH": "${env.GIT_BRANCH}"
}
}"""
)
def result = readJSON text: response.content
if (!result.result.approved) {
error "Deployment not approved: ${result.result.findings}"
}
}
}
}
stage('Deploy') {
steps {
sh './deploy.sh production'
}
}
stage('Health Check') {
steps {
script {
def response = httpRequest(
url: 'https://api.nexus.app/v1/tasks/post-deploy-health/execute',
httpMode: 'POST',
customHeaders: [[name: 'Authorization', value: "Bearer ${NEXUS_API_KEY}"]],
contentType: 'APPLICATION_JSON',
requestBody: '{"parameters": {"APP_URL": "https://app.miempresa.com"}}'
)
def result = readJSON text: response.content
if (!result.result.healthy) {
sh './rollback.sh'
error "Health check failed: ${result.result.issues}"
}
}
}
}
}
post {
failure {
// Notificar a Nexus del fallo
httpRequest(
url: 'https://api.nexus.app/v1/tasks/notify-failure/execute',
httpMode: 'POST',
customHeaders: [[name: 'Authorization', value: "Bearer ${NEXUS_API_KEY}"]]
)
}
}
}
Paso 5: Configura notificaciones¶
En Nexus, crea una tarea para notificaciones:
Prompt:
Envía notificación del estado del deployment.
Estado: ${STATUS}
Commit: ${COMMIT_SHA}
Branch: ${BRANCH}
Detalles: ${DETAILS}
Envía mensaje a Slack con formato rico incluyendo:
- Estado con emoji (✅/❌)
- Link al commit
- Resumen de cambios
- Siguiente acción recomendada si falló
Verificación¶
Tu integración está completa si:
- [ ] Un push a main dispara el pipeline
- [ ] Nexus valida el código antes del deploy
- [ ] El health check verifica el despliegue
- [ ] Recibes notificaciones de cada paso
Buenas prácticas¶
Timeouts
Configura timeouts adecuados para las llamadas a Nexus (30-60 segundos).
Reintentos
Implementa reintentos en caso de fallos de red.
Logs
Guarda los logs de validación de Nexus para auditoría.
Siguiente: Monitoreo proactivo - Detecta problemas antes.