Files
iac-duplicate/scripts/validate-environment.sh
Jenkins CI 71be2abd2e Add complete SACC v4 infrastructure project
- Terraform modules: VPC, EC2, RDS, S3, CloudFront, Route53, Lambda, IAM, Security Groups
- Ansible playbooks for server configuration
- Scripts: create-test-environment.sh, destroy-test-environment.sh, validate-environment.sh
- Documentation: README, QUICKSTART, AGENTS
- Jenkins pipeline for automated deployment
- Jenkins pipeline for environment destruction
2026-06-03 04:39:01 +00:00

534 lines
17 KiB
Bash
Executable File

#!/bin/bash
# =============================================================================
# SACC v4 - Script de Validacion de Entorno TEST
# =============================================================================
# Verifica que todos los componentes del entorno de test funcionen correctamente.
#
# USO:
# ./validate-environment.sh [opciones]
#
# OPCIONES:
# --full Ejecutar todas las validaciones (default)
# --ssh-only Solo validar conectividad SSH
# --services Solo validar servicios systemd
# --api Solo validar APIs
# --nginx Solo validar nginx
# --rds Solo validar RDS
# --s3 Solo validar S3
# --help Mostrar ayuda
#
# IMPORTANTE: Requiere que el entorno haya sido creado previamente
# =============================================================================
set -euo pipefail
# Colores
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
# =============================================================================
# CONFIGURACION
# =============================================================================
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
TERRAFORM_DIR="$PROJECT_ROOT/terraform/environments/test"
LOG_FILE="$PROJECT_ROOT/logs/validate-$(date +%Y%m%d-%H%M%S).log"
mkdir -p "$(dirname "$LOG_FILE")"
# Flags
CHECK_SSH=true
CHECK_SERVICES=true
CHECK_API=true
CHECK_NGINX=true
CHECK_RDS=true
CHECK_S3=true
CHECK_CLOUDFRONT=true
# =============================================================================
# FUNCIONES
# =============================================================================
log() {
echo -e "${GREEN}[$(date '+%H:%M:%S')] OK:${NC} $1" | tee -a "$LOG_FILE"
}
warn() {
echo -e "${YELLOW}[$(date '+%H:%M:%S')] WARN:${NC} $1" | tee -a "$LOG_FILE"
}
error() {
echo -e "${RED}[$(date '+%H:%M:%S')] FAIL:${NC} $1" | tee -a "$LOG_FILE"
}
info() {
echo -e "${BLUE}[$(date '+%H:%M:%S')] INFO:${NC} $1" | tee -a "$LOG_FILE"
}
# =============================================================================
# PARSEAR ARGUMENTOS
# =============================================================================
parse_args() {
if [ $# -eq 0 ]; then
return
fi
# Desactivar todo primero
CHECK_SSH=false
CHECK_SERVICES=false
CHECK_API=false
CHECK_NGINX=false
CHECK_RDS=false
CHECK_S3=false
CHECK_CLOUDFRONT=false
while [ $# -gt 0 ]; do
case "$1" in
--full)
CHECK_SSH=true
CHECK_SERVICES=true
CHECK_API=true
CHECK_NGINX=true
CHECK_RDS=true
CHECK_S3=true
CHECK_CLOUDFRONT=true
;;
--ssh-only)
CHECK_SSH=true
;;
--services)
CHECK_SERVICES=true
;;
--api)
CHECK_API=true
;;
--nginx)
CHECK_NGINX=true
;;
--rds)
CHECK_RDS=true
;;
--s3)
CHECK_S3=true
;;
--help)
echo "Uso: $0 [opciones]"
echo ""
echo "Opciones:"
echo " --full Ejecutar todas las validaciones (default)"
echo " --ssh-only Solo validar conectividad SSH"
echo " --services Solo validar servicios systemd"
echo " --api Solo validar APIs"
echo " --nginx Solo validar nginx"
echo " --rds Solo validar RDS"
echo " --s3 Solo validar S3"
echo " --help Mostrar esta ayuda"
exit 0
;;
*)
echo "Opcion desconocida: $1"
echo "Usar --help para ver opciones disponibles"
exit 1
;;
esac
shift
done
}
# =============================================================================
# OBTENER DATOS DE TERRAFORM
# =============================================================================
get_terraform_outputs() {
if [ ! -d "$TERRAFORM_DIR" ]; then
error "No existe directorio Terraform: $TERRAFORM_DIR"
return 1
fi
cd "$TERRAFORM_DIR"
if [ ! -f "terraform.tfstate" ] && [ ! -d ".terraform" ]; then
error "No existe estado de Terraform. Ejecutar create-test-environment.sh primero."
return 1
fi
EC2_IP=$(terraform output -raw ec2_public_ip 2>/dev/null || echo "")
RDS_ENDPOINT=$(terraform output -raw rds_endpoint 2>/dev/null || echo "")
S3_BUCKET=$(terraform output -raw frontend_bucket_name 2>/dev/null || echo "")
CLOUDFRONT_DOMAIN=$(terraform output -raw cloudfront_domain_name 2>/dev/null || echo "")
VPC_ID=$(terraform output -raw vpc_id 2>/dev/null || echo "")
if [ -z "$EC2_IP" ]; then
error "No se pudo obtener EC2_IP del estado de Terraform"
return 1
fi
info "Datos del entorno:"
info " EC2 IP: $EC2_IP"
info " RDS: $RDS_ENDPOINT"
info " S3: $S3_BUCKET"
info " CloudFront: $CLOUDFRONT_DOMAIN"
}
# =============================================================================
# VALIDAR SSH
# =============================================================================
check_ssh() {
info "========================================"
info "VALIDANDO CONECTIVIDAD SSH"
info "========================================"
local ssh_key="$HOME/.ssh/sacc4-test-key.pem"
if [ ! -f "$ssh_key" ]; then
warn "No existe llave SSH: $ssh_key"
return 1
fi
if ssh -i "$ssh_key" -o StrictHostKeyChecking=no -o ConnectTimeout=10 -o BatchMode=yes ubuntu@"$EC2_IP" "echo 'SSH_OK'" > /dev/null 2>&1; then
log "SSH conectividad: OK ($EC2_IP)"
else
error "SSH conectividad: FALLIDA ($EC2_IP)"
return 1
fi
# Verificar usuarios
for user in ubuntu thoth osiris; do
if ssh -i "$ssh_key" -o StrictHostKeyChecking=no ubuntu@"$EC2_IP" "id $user" > /dev/null 2>&1; then
log "Usuario $user: Existe"
else
warn "Usuario $user: No encontrado"
fi
done
}
# =============================================================================
# VALIDAR SERVICIOS SYSTEMD
# =============================================================================
check_services() {
info "========================================"
info "VALIDANDO SERVICIOS SYSTEMD"
info "========================================"
local ssh_key="$HOME/.ssh/sacc4-test-key.pem"
local services=("nginx")
local api_services=(
"api-sacc4-authentication"
"api-sacc4-users"
"api-sacc4-tickets"
"api-sacc4-privileges"
"api-sacc4-rols"
"api-sacc4-associates"
)
# Nginx
if ssh -i "$ssh_key" -o StrictHostKeyChecking=no ubuntu@"$EC2_IP" "sudo systemctl is-active nginx" > /dev/null 2>&1; then
log "nginx: Activo"
else
error "nginx: Inactivo o no encontrado"
fi
# Servicios API
for service in "${api_services[@]}"; do
local status
status=$(ssh -i "$ssh_key" -o StrictHostKeyChecking=no ubuntu@"$EC2_IP" "sudo systemctl is-active $service 2>/dev/null || echo 'inactive'")
if [ "$status" == "active" ]; then
log "$service: Activo"
else
warn "$service: $status (esperar despliegue de JARs)"
fi
done
# Verificar que los servicios estan habilitados
for service in "${api_services[@]}"; do
local enabled
enabled=$(ssh -i "$ssh_key" -o StrictHostKeyChecking=no ubuntu@"$EC2_IP" "sudo systemctl is-enabled $service 2>/dev/null || echo 'disabled'")
if [ "$enabled" == "enabled" ]; then
log "$service: Habilitado para inicio automatico"
else
warn "$service: No habilitado ($enabled)"
fi
done
}
# =============================================================================
# VALIDAR APIs (PUERTOS 8080-8085)
# =============================================================================
check_api() {
info "========================================"
info "VALIDANDO APIs (Puertos 8080-8085)"
info "========================================"
local ssh_key="$HOME/.ssh/sacc4-test-key.pem"
local services=(
"8080:api-sacc4-authentication"
"8081:api-sacc4-users"
"8082:api-sacc4-tickets"
"8083:api-sacc4-privileges"
"8084:api-sacc4-rols"
"8085:api-sacc4-associates"
)
for svc in "${services[@]}"; do
local port=$(echo "$svc" | cut -d':' -f1)
local name=$(echo "$svc" | cut -d':' -f2)
# Verificar si el puerto esta escuchando
if ssh -i "$ssh_key" -o StrictHostKeyChecking=no ubuntu@"$EC2_IP" "ss -tlnp | grep -q ':$port '" 2>/dev/null; then
log "$name (puerto $port): Escuchando"
# Intentar health check
local health_status
health_status=$(ssh -i "$ssh_key" -o StrictHostKeyChecking=no ubuntu@"$EC2_IP" "curl -s -o /dev/null -w '%{http_code}' http://localhost:$port/actuator/health 2>/dev/null || echo '000'")
if [ "$health_status" == "200" ]; then
log "$name (puerto $port): Health check OK (HTTP 200)"
else
warn "$name (puerto $port): Health check responde HTTP $health_status"
fi
else
warn "$name (puerto $port): No esta escuchando"
fi
done
}
# =============================================================================
# VALIDAR NGINX
# =============================================================================
check_nginx() {
info "========================================"
info "VALIDANDO NGINX"
info "========================================"
local ssh_key="$HOME/.ssh/sacc4-test-key.pem"
# Configuracion
if ssh -i "$ssh_key" -o StrictHostKeyChecking=no ubuntu@"$EC2_IP" "sudo nginx -t" > /dev/null 2>&1; then
log "nginx -t: Configuracion valida"
else
error "nginx -t: Errores en configuracion"
fi
# Procesos
local workers
workers=$(ssh -i "$ssh_key" -o StrictHostKeyChecking=no ubuntu@"$EC2_IP" "ps aux | grep '[n]ginx: worker' | wc -l")
if [ "$workers" -gt 0 ]; then
log "nginx: $workers workers activos"
else
warn "nginx: No hay workers activos"
fi
# Puerto 80
if ssh -i "$ssh_key" -o StrictHostKeyChecking=no ubuntu@"$EC2_IP" "ss -tlnp | grep -q ':80 '" > /dev/null 2>&1; then
log "nginx: Puerto 80 escuchando"
else
error "nginx: Puerto 80 no escucha"
fi
# Puerto 443
if ssh -i "$ssh_key" -o StrictHostKeyChecking=no ubuntu@"$EC2_IP" "ss -tlnp | grep -q ':443 '" > /dev/null 2>&1; then
log "nginx: Puerto 443 escuchando (SSL configurado)"
else
warn "nginx: Puerto 443 no escucha (SSL no configurado)"
fi
}
# =============================================================================
# VALIDAR RDS
# =============================================================================
check_rds() {
info "========================================"
info "VALIDANDO RDS (MariaDB)"
info "========================================"
local ssh_key="$HOME/.ssh/sacc4-test-key.pem"
# Verificar conectividad de red
if ssh -i "$ssh_key" -o StrictHostKeyChecking=no ubuntu@"$EC2_IP" "nc -z -w 5 $(echo $RDS_ENDPOINT | cut -d':' -f1) 3306" > /dev/null 2>&1; then
log "RDS: Conectividad de red OK (puerto 3306)"
else
error "RDS: No se puede conectar al puerto 3306"
return 1
fi
# Verificar login (usando usuario de aplicacion)
if ssh -i "$ssh_key" -o StrictHostKeyChecking=no ubuntu@"$EC2_IP" "mysql -h $RDS_ENDPOINT -u sacc_app_user -p -e 'SELECT 1;' 2>/dev/null" > /dev/null 2>&1; then
log "RDS: Login como sacc_app_user OK"
else
warn "RDS: No se pudo hacer login (verificar credenciales en /etc/sacc4/sacc4.env)"
fi
# Listar bases de datos
local databases
databases=$(ssh -i "$ssh_key" -o StrictHostKeyChecking=no ubuntu@"$EC2_IP" "mysql -h $RDS_ENDPOINT -u sacc_app_user -p -e 'SHOW DATABASES;' 2>/dev/null || true")
if [ -n "$databases" ]; then
log "RDS: Bases de datos disponibles:"
echo "$databases" | while read -r db; do
info " - $db"
done
fi
}
# =============================================================================
# VALIDAR S3
# =============================================================================
check_s3() {
info "========================================"
info "VALIDANDO S3 (Frontend)"
info "========================================"
if [ -z "$S3_BUCKET" ]; then
warn "S3: No se pudo obtener nombre del bucket"
return 1
fi
# Verificar que el bucket existe
if aws s3api head-bucket --bucket "$S3_BUCKET" 2>/dev/null; then
log "S3: Bucket existe ($S3_BUCKET)"
else
error "S3: Bucket no existe o no es accesible ($S3_BUCKET)"
return 1
fi
# Listar contenido
local objects
objects=$(aws s3 ls "s3://$S3_BUCKET" --summarize 2>/dev/null | tail -2)
if [ -n "$objects" ]; then
log "S3: Contenido del bucket:"
aws s3 ls "s3://$S3_BUCKET" | head -10 | while read -r line; do
info " $line"
done
else
warn "S3: Bucket vacio (subir build del frontend)"
fi
# Politica del bucket
local policy
policy=$(aws s3api get-bucket-policy --bucket "$S3_BUCKET" --query 'Policy' --output text 2>/dev/null || echo "No policy")
if [ "$policy" != "No policy" ]; then
log "S3: Politica de bucket configurada"
else
warn "S3: No hay politica de bucket configurada"
fi
}
# =============================================================================
# VALIDAR CLOUDFRONT
# =============================================================================
check_cloudfront() {
info "========================================"
info "VALIDANDO CLOUDFRONT"
info "========================================"
if [ -z "$CLOUDFRONT_DOMAIN" ]; then
warn "CloudFront: No se pudo obtener dominio"
return 1
fi
log "CloudFront: Dominio = $CLOUDFRONT_DOMAIN"
# Verificar distribucion
local dist_id
dist_id=$(aws cloudfront list-distributions --query "DistributionList.Items[?DomainName=='$CLOUDFRONT_DOMAIN'].Id" --output text 2>/dev/null || echo "")
if [ -n "$dist_id" ]; then
log "CloudFront: Distribucion encontrada (ID: $dist_id)"
# Verificar estado
local status
status=$(aws cloudfront get-distribution --id "$dist_id" --query 'Distribution.Status' --output text 2>/dev/null || echo "Unknown")
if [ "$status" == "Deployed" ]; then
log "CloudFront: Estado = Deployed"
else
warn "CloudFront: Estado = $status"
fi
else
warn "CloudFront: No se encontro distribucion"
fi
}
# =============================================================================
# RESUMEN
# =============================================================================
show_summary() {
info "========================================"
info "RESUMEN DE VALIDACION"
info "========================================"
local ok_count=$(grep -c "OK:" "$LOG_FILE" 2>/dev/null || echo 0)
local warn_count=$(grep -c "WARN:" "$LOG_FILE" 2>/dev/null || echo 0)
local fail_count=$(grep -c "FAIL:" "$LOG_FILE" 2>/dev/null || echo 0)
log "Validaciones exitosas: $ok_count"
if [ "$warn_count" -gt 0 ]; then
warn "Advertencias: $warn_count"
fi
if [ "$fail_count" -gt 0 ]; then
error "Fallos: $fail_count"
fi
info ""
info "Log completo: $LOG_FILE"
info ""
info "URLs del entorno:"
info " API: http://$EC2_IP"
info " API SSL: https://$EC2_IP (si SSL configurado)"
info " Front: https://$CLOUDFRONT_DOMAIN"
}
# =============================================================================
# MAIN
# =============================================================================
main() {
parse_args "$@"
info "========================================"
info "SACC v4 - Validacion de Entorno TEST"
info "========================================"
get_terraform_outputs
if [ "$CHECK_SSH" == "true" ]; then
check_ssh
fi
if [ "$CHECK_SERVICES" == "true" ]; then
check_services
fi
if [ "$CHECK_API" == "true" ]; then
check_api
fi
if [ "$CHECK_NGINX" == "true" ]; then
check_nginx
fi
if [ "$CHECK_RDS" == "true" ]; then
check_rds
fi
if [ "$CHECK_S3" == "true" ]; then
check_s3
fi
if [ "$CHECK_CLOUDFRONT" == "true" ]; then
check_cloudfront
fi
show_summary
}
main "$@"