#!/bin/bash ############################################################################### # Script de Validación de Conexión EC2 → RDS (MariaDB) # Proyecto: proyectosacc (SACC4) - Entorno DEV # Servidor: proyectosacc-api-dev (78.12.135.184) # Base de datos: proyectosacc-db-dev ############################################################################### # ───────────────────────────────────────────────────────────────────────────── # CONFIGURACIÓN - Modifica estos valores según tu entorno # ───────────────────────────────────────────────────────────────────────────── RDS_HOST="proyectosacc-db-dev.cbe2keowyu6w.mx-central-1.rds.amazonaws.com" RDS_PORT="3306" RDS_USER="${DEV_DB_USERNAME:-admin}" # Usa variable de entorno o default RDS_PASSWORD="${DEV_DB_PASSWORD:-}" # Se espera como variable de entorno RDS_DBNAME="${DEV_DB_NAME:-proyectosacc_dev}" # Nombre de la base de datos EC2_IP="78.12.135.184" TIMEOUT_SECONDS="10" # Colores para output RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' BLUE='\033[0;34m' NC='\033[0m' # No Color BOLD='\033[1m' # ───────────────────────────────────────────────────────────────────────────── # FUNCIONES AUXILIARES # ───────────────────────────────────────────────────────────────────────────── print_header() { echo -e "\n${BOLD}═══════════════════════════════════════════════════════════════${NC}" echo -e "${BOLD} $1${NC}" echo -e "${BOLD}═══════════════════════════════════════════════════════════════${NC}" } print_success() { echo -e "${GREEN}✅ $1${NC}" } print_error() { echo -e "${RED}❌ $1${NC}" } print_warning() { echo -e "${YELLOW}⚠️ $1${NC}" } print_info() { echo -e "${BLUE}ℹ️ $1${NC}" } # ───────────────────────────────────────────────────────────────────────────── # VALIDACIÓN DE PREREQUISITOS # ───────────────────────────────────────────────────────────────────────────── print_header "1. VALIDACIÓN DE PREREQUISITOS" # Verificar que estamos en el servidor correcto CURRENT_IP=$(hostname -I | awk '{print $1}') print_info "IP actual del servidor: $CURRENT_IP" print_info "IP esperada (EC2 DEV): $EC2_IP" if [ "$CURRENT_IP" != "$EC2_IP" ]; then print_warning "La IP actual ($CURRENT_IP) no coincide con la IP esperada ($EC2_IP)" print_warning "Asegúrate de estar ejecutando este script en el servidor DEV" else print_success "IP verificada correctamente" fi # Verificar herramientas necesarias echo -e "\n${BOLD}Verificando herramientas instaladas:${NC}" check_tool() { if command -v "$1" &> /dev/null; then VERSION=$($2 2>/dev/null | head -1) print_success "$1 instalado - $VERSION" return 0 else print_error "$1 NO está instalado" return 1 fi } NEED_MYSQL=0 check_tool "nc" "nc --version" || NEED_MYSQL=1 check_tool "telnet" "telnet --version" 2>/dev/null || true check_tool "mysql" "mysql --version" || NEED_MYSQL=1 if [ $NEED_MYSQL -eq 1 ]; then print_warning "Se recomienda instalar: mariadb-client o mysql-client" print_info "Ejecuta: sudo apt-get update && sudo apt-get install -y mariadb-client" fi # ───────────────────────────────────────────────────────────────────────────── # PRUEBA 1: RESOLUCIÓN DNS # ───────────────────────────────────────────────────────────────────────────── print_header "2. RESOLUCIÓN DNS" print_info "Resolviendo: $RDS_HOST" if command -v dig &> /dev/null; then RDS_IP=$(dig +short "$RDS_HOST" | head -1) if [ -n "$RDS_IP" ]; then print_success "DNS resuelto: $RDS_HOST → $RDS_IP" dig +short "$RDS_HOST" | while read ip; do print_info " IP encontrada: $ip" done else print_error "No se pudo resolver el DNS de $RDS_HOST" print_info "Verifica la configuración de DNS o la conectividad a internet" fi elif command -v nslookup &> /dev/null; then nslookup "$RDS_HOST" 2>&1 | grep -E "Address:|Name:" | while read line; do print_info " $line" done else print_warning "No se encontró 'dig' ni 'nslookup'. Instala dnsutils:" print_info " sudo apt-get install -y dnsutils" fi # ───────────────────────────────────────────────────────────────────────────── # PRUEBA 2: CONECTIVIDAD DE RED (Ping) # ───────────────────────────────────────────────────────────────────────────── print_header "3. CONECTIVIDAD DE RED (Ping)" print_info "Haciendo ping a $RDS_HOST..." if ping -c 3 -W 5 "$RDS_HOST" &> /dev/null; then print_success "Ping exitoso - El servidor RDS responde" ping -c 1 -W 5 "$RDS_HOST" | grep -E "time=|ttl=" | while read line; do print_info " $line" done else print_error "Ping fallido - No hay respuesta del servidor RDS" print_info "Esto puede ser normal si RDS tiene ICMP bloqueado" fi # ───────────────────────────────────────────────────────────────────────────── # PRUEBA 3: CONEXIÓN DE PUERTO TCP # ───────────────────────────────────────────────────────────────────────────── print_header "4. CONEXIÓN DE PUERTO TCP (Puerto $RDS_PORT)" print_info "Verificando si el puerto $RDS_PORT está abierto en $RDS_HOST..." if command -v nc &> /dev/null; then if nc -zv -w "$TIMEOUT_SECONDS" "$RDS_HOST" "$RDS_PORT" 2>&1 | grep -q "succeeded\|open"; then print_success "Puerto $RDS_PORT ABIERTO - Conexión TCP exitosa" else print_error "Puerto $RDS_PORT CERRADO o bloqueado" print_info "Verifica:" print_info " 1. Security Group de RDS (debe permitir entrada desde $EC2_IP)" print_info " 2. Network ACLs" print_info " 3. Firewall del servidor EC2 (iptables/ufw)" fi nc -zv -w "$TIMEOUT_SECONDS" "$RDS_HOST" "$RDS_PORT" 2>&1 | while read line; do print_info " $line" done elif command -v telnet &> /dev/null; then print_info "Usando telnet (Ctrl+C para cancelar si se cuelga)..." timeout 5 bash -c "echo >/dev/tcp/$RDS_HOST/$RDS_PORT" 2>/dev/null if [ $? -eq 0 ]; then print_success "Puerto $RDS_PORT ABIERTO" else print_error "Puerto $RDS_PORT CERRADO" fi else print_warning "No se encontró 'nc' ni 'telnet'. Usando /dev/tcp..." timeout 5 bash -c "echo >/dev/tcp/$RDS_HOST/$RDS_PORT" 2>/dev/null if [ $? -eq 0 ]; then print_success "Puerto $RDS_PORT ABIERTO" else print_error "Puerto $RDS_PORT CERRADO" fi fi # ───────────────────────────────────────────────────────────────────────────── # PRUEBA 4: CONEXIÓN A BASE DE DATOS (MySQL/MariaDB) # ───────────────────────────────────────────────────────────────────────────── print_header "5. CONEXIÓN A BASE DE DATOS (MariaDB)" if ! command -v mysql &> /dev/null; then print_error "Cliente MySQL/MariaDB no instalado" print_info "Instala con: sudo apt-get install -y mariadb-client" print_info "Saltando prueba de conexión a BD..." else if [ -z "$RDS_PASSWORD" ]; then print_warning "No se encontró DEV_DB_PASSWORD en las variables de entorno" print_info "Exporta la variable antes de ejecutar:" print_info " export DEV_DB_PASSWORD='tu_password_aquí'" print_info "O ejecuta el script con: DEV_DB_PASSWORD='xxx' ./validar_conexion_rds.sh" else print_info "Intentando conectar a MariaDB..." # Prueba de conexión simple if mysql -h "$RDS_HOST" -P "$RDS_PORT" -u "$RDS_USER" -p"$RDS_PASSWORD" \ -e "SELECT 'Conexión exitosa' as status, NOW() as server_time;" 2>/dev/null; then print_success "¡CONEXIÓN EXITOSA A LA BASE DE DATOS!" # Información del servidor echo -e "\n${BOLD}Información del servidor MariaDB:${NC}" mysql -h "$RDS_HOST" -P "$RDS_PORT" -u "$RDS_USER" -p"$RDS_PASSWORD" \ -e "SELECT VERSION() as version;" 2>/dev/null | grep -v "version" | while read line; do print_info " Versión: $line" done # Listar bases de datos echo -e "\n${BOLD}Bases de datos disponibles:${NC}" mysql -h "$RDS_HOST" -P "$RDS_PORT" -u "$RDS_USER" -p"$RDS_PASSWORD" \ -e "SHOW DATABASES;" 2>/dev/null | grep -v "Database" | grep -v "information_schema\|performance_schema\|mysql" | while read db; do print_info " 📁 $db" done # Verificar base de datos específica if [ -n "$RDS_DBNAME" ]; then echo -e "\n${BOLD}Verificando base de datos '$RDS_DBNAME':${NC}" mysql -h "$RDS_HOST" -P "$RDS_PORT" -u "$RDS_USER" -p"$RDS_PASSWORD" \ -e "SHOW TABLES FROM \`$RDS_DBNAME\`;" 2>/dev/null | head -20 | while read table; do if [ "$table" != "Tables_in_$RDS_DBNAME" ]; then print_info " 📋 $table" fi done fi else print_error "No se pudo conectar a la base de datos" print_info "Posibles causas:" print_info " 1. Credenciales incorrectas (usuario/password)" print_info " 2. Usuario no tiene permisos desde esta IP" print_info " 3. Base de datos no existe" # Intentar obtener más información del error echo -e "\n${BOLD}Detalle del error:${NC}" mysql -h "$RDS_HOST" -P "$RDS_PORT" -u "$RDS_USER" -p"$RDS_PASSWORD" \ -e "SELECT 1;" 2>&1 | grep -v "Warning:" | while read line; do print_error " $line" done fi fi fi # ───────────────────────────────────────────────────────────────────────────── # PRUEBA 5: VERIFICACIÓN DE VARIABLES DE ENTORNO # ───────────────────────────────────────────────────────────────────────────── print_header "6. VARIABLES DE ENTORNO CONFIGURADAS" echo -e "${BOLD}Variables encontradas:${NC}" vars_found=0 for var in DEV_DB_HOST DEV_DB_PORT DEV_DB_NAME DEV_DB_USERNAME DEV_DB_PASSWORD; do if [ -n "${!var}" ]; then if [ "$var" = "DEV_DB_PASSWORD" ]; then print_success "$var=********** (oculto)" else print_success "$var=${!var}" fi vars_found=$((vars_found + 1)) else print_error "$var=NO DEFINIDO" fi done echo -e "\n${BOLD}Resumen:${NC}" if [ $vars_found -eq 5 ]; then print_success "Todas las variables de entorno están configuradas" elif [ $vars_found -gt 0 ]; then print_warning "Solo $vars_found/5 variables configuradas" else print_error "Ninguna variable de entorno configurada" print_info "Crea un archivo .env con las variables necesarias:" cat << 'EOF' # Ejemplo de archivo .env echo "export DEV_DB_HOST=proyectosacc-db-dev.cbe2keowyu6w.mx-central-1.rds.amazonaws.com" >> .env echo "export DEV_DB_PORT=3306" >> .env echo "export DEV_DB_NAME=proyectosacc_dev" >> .env echo "export DEV_DB_USERNAME=admin" >> .env echo "export DEV_DB_PASSWORD=tu_password_aqui" >> .env # Cargar variables: source .env EOF fi # ───────────────────────────────────────────────────────────────────────────── # PRUEBA 6: CONFIGURACIÓN DE AWS CLI (Opcional) # ───────────────────────────────────────────────────────────────────────────── print_header "7. CONFIGURACIÓN DE AWS CLI (Opcional)" if command -v aws &> /dev/null; then print_success "AWS CLI instalado" # Verificar configuración if aws sts get-caller-identity &> /dev/null; then print_success "AWS CLI configurado correctamente" aws sts get-caller-identity 2>/dev/null | grep -E "Account|Arn" | while read line; do print_info " $line" done else print_warning "AWS CLI no está configurado o credenciales inválidas" print_info "Configura con: aws configure" fi # Verificar información del RDS desde AWS echo -e "\n${BOLD}Información del RDS desde AWS CLI:${NC}" aws rds describe-db-instances \ --query 'DBInstances[?DBInstanceIdentifier==`proyectosacc-db-dev`].[DBInstanceIdentifier,DBInstanceStatus,Endpoint.Address,AvailabilityZone]' \ --output table 2>/dev/null || print_error "No se pudo obtener información del RDS" else print_warning "AWS CLI no instalado (opcional para diagnóstico)" print_info "Instala con: sudo apt-get install -y awscli" fi # ───────────────────────────────────────────────────────────────────────────── # RESUMEN FINAL # ───────────────────────────────────────────────────────────────────────────── print_header "RESUMEN FINAL DE VALIDACIÓN" echo -e "${BOLD}Conexión:${NC} EC2 DEV ($EC2_IP) → RDS DEV ($RDS_HOST:$RDS_PORT)" echo "" # Hacer resumen basado en las pruebas print_info "✓ Verifica la resolución DNS del endpoint RDS" print_info "✓ Verifica conectividad de red (ping/TCP)" print_info "✓ Verifica conexión a MariaDB/MySQL" print_info "✓ Verifica variables de entorno" echo -e "\n${BOLD}Si todo está ✅:${NC}" print_success "Tu servidor EC2 puede conectarse correctamente al RDS" echo -e "\n${BOLD}Si hay ❌:${NC}" print_info "1. Revisa Security Groups: Grupo de seguridad de RDS debe permitir entrada TCP 3306 desde $EC2_IP" print_info "2. Revisa Network ACLs de la VPC" print_info "3. Revisa firewall local: sudo iptables -L -n | grep 3306" print_info "4. Verifica que el endpoint RDS sea correcto" print_info "5. Verifica credenciales de la base de datos" echo -e "\n${BOLD}Comandos útiles para diagnóstico:${NC}" echo " # Ver logs de conexión (en EC2):" echo " sudo tail -f /var/log/syslog | grep -i mariadb" echo "" echo " # Ver reglas de firewall:" echo " sudo iptables -L -n | grep 3306" echo "" echo " # Test manual de conexión MySQL:" echo " mysql -h $RDS_HOST -P $RDS_PORT -u -p" echo "" echo " # Ver Security Groups desde AWS:" echo " aws ec2 describe-security-groups --query 'SecurityGroups[*].[GroupName,GroupId]'" echo -e "\n${GREEN}${BOLD}Script completado.${NC}"