diff --git a/DATOS_CONEXION.md b/DATOS_CONEXION.md index f0c768d..a86a9b2 100644 --- a/DATOS_CONEXION.md +++ b/DATOS_CONEXION.md @@ -9,6 +9,22 @@ | PROD | 78.12.139.51 | thoth | bitbucket_thoth | | PROD | 78.12.139.51 | osiris | bitbucket_osiris | +## Base de Datos (RDS) + +| Entorno | Endpoint | Base de Datos | Usuario | +|---------|----------|---------------|---------| +| DEV | proyectosacc-db-dev.cbe2keowyu6w.mx-central-1.rds.amazonaws.com:3306 | ccsoft_sacc4 | sacc_admin_dev | + +### Credenciales + +``` +DEV_DB_HOST=proyectosacc-db-dev.cbe2keowyu6w.mx-central-1.rds.amazonaws.com +DEV_DB_PORT=3306 +DEV_DB_NAME=ccsoft_sacc4 +DEV_DB_USERNAME=sacc_admin_dev +DEV_DB_PASSWORD=AiIRgWAM7RDB2VBuDlrXKBKyE +``` + ## Variables de Bitbucket ``` @@ -19,13 +35,56 @@ SSH_PRIVATE_KEY_OSIRIS=(contenido de keys/osiris_key) ``` ## Archivos de Llaves -- `keys/thoth_key` - Llave privada para usuario thoth +- `keys/thoth_key` - Llave privada para usuario thoth (πŸ”’ **con passphrase**) - `keys/thoth_key.pub` - Llave pΓΊblica para usuario thoth -- `keys/osiris_key` - Llave privada para usuario osiris +- `keys/osiris_key` - Llave privada para usuario osiris (πŸ”’ **con passphrase**) - `keys/osiris_key.pub` - Llave pΓΊblica para usuario osiris +- `keys/*.old` - Backups de llaves antiguas (sin passphrase) + +## βœ… ESTADO: Llaves Actualizadas en Servidor DEV + +### Passphrases (GUARDAR EN LUGAR SEGURO) + +| Usuario | Passphrase | +|---------|------------| +| **thoth** | `fEbr9CoAlfllHDhocAbRo+aja+SW72a5` | +| **osiris** | `2/GkAjmPF8v0KNuWS6DC3IbyjNmP/Cfh` | + +### ConexiΓ³n de Prueba βœ… VERIFICADO -## ConexiΓ³n de Prueba ```bash +# Conectar como thoth (te pedirΓ‘ la passphrase) ssh -i keys/thoth_key thoth@78.12.135.184 + +# Conectar como osiris (te pedirΓ‘ la passphrase) ssh -i keys/osiris_key osiris@78.12.135.184 + +# Usar ssh-agent para no escribir la passphrase cada vez + eval "$(ssh-agent -s)" + ssh-add keys/thoth_key + ssh -i keys/thoth_key thoth@78.12.135.184 ``` + +### Nuevas Llaves PΓΊblicas (ya autorizadas en servidor DEV) + +**thoth:** +``` +ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMxH0Gp40+3sGhiWRL5lByTSbdcIcRe1XSWQvPW74JlQ thoth@ccsoft.ai +``` + +**osiris:** +``` +ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFo6CycfgIuCCSVZbhuPwqlAVDxY8YWb1xpvpqxSzMjR osiris@ccsoft.ai +``` + +### ⚠️ IMPORTANTE: Impacto en CI/CD + +Las llaves con passphrase **romperΓ‘n el pipeline CI/CD** a menos que configures `ssh-agent` en Bitbucket Pipelines. Para el pipeline, necesitarΓ‘s: +1. Usar `ssh-agent` en el pipeline, o +2. Crear llaves separadas SOLO para CI/CD (sin passphrase) + +### Backups Disponibles + +Las llaves antiguas (sin passphrase) se guardaron como backup: +- `keys/thoth_key.old` +- `keys/osiris_key.old` diff --git a/bitbucket-pipelines.yml b/bitbucket-pipelines.yml index dc5203d..1f232e4 100644 --- a/bitbucket-pipelines.yml +++ b/bitbucket-pipelines.yml @@ -68,7 +68,7 @@ pipelines: name: 01_image-setup script: - set -euo pipefail - - apt-get update -y && apt-get install -y openssh-client openjdk-21-jdk wget unzip curl + - apt-get update -y && apt-get install -y openssh-client openjdk-21-jdk wget unzip curl expect - curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" - unzip -q awscliv2.zip - ./aws/install @@ -77,6 +77,14 @@ pipelines: - echo "${SSH_PRIVATE_KEY_THOTH}" > ~/.ssh/sacc4_key - chmod 600 ~/.ssh/sacc4_key - ssh-keyscan -p "22" "${DEV_INSTANCE_IP}" >> ~/.ssh/known_hosts 2>/dev/null || true + - eval "$(ssh-agent -s)" + - | + expect -c " + spawn ssh-add ~/.ssh/sacc4_key + expect \"Enter passphrase\" + send \"${SSH_PASSPHRASE_THOTH}\r\" + expect eof + " - export TELEGRAM_BOT_TOKEN="${DEV_TELEGRAM_BOT_TOKEN}" - export TELEGRAM_CHAT_ID="${DEV_TELEGRAM_CHAT_ID}" - bash scripts/telegram-pipeline-notify.sh start @@ -177,11 +185,18 @@ pipelines: name: 06_update_ssh_keys script: - set -euo pipefail + - apt-get update -y && apt-get install -y expect - mkdir -p ~/.ssh - echo "${SSH_PRIVATE_KEY_THOTH}" > ~/.ssh/sacc4_key - chmod 600 ~/.ssh/sacc4_key - # Actualizar authorized_keys del usuario thoth con la llave pΓΊblica del pipeline - # Esto asegura que solo el pipeline actual pueda acceder, rotando llaves automΓ‘ticamente + - eval "$(ssh-agent -s)" + - | + expect -c " + spawn ssh-add ~/.ssh/sacc4_key + expect \"Enter passphrase\" + send \"${SSH_PASSPHRASE_THOTH}\r\" + expect eof + " - | DEV_PUB_KEY=$(echo "${SSH_PRIVATE_KEY_THOTH}" | ssh-keygen -y -f /dev/stdin) ssh -p "22" \ @@ -195,7 +210,7 @@ pipelines: name: 07_install script: - set -euo pipefail - - apt-get update -y && apt-get install -y curl unzip + - apt-get update -y && apt-get install -y curl unzip expect - curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" - unzip -q awscliv2.zip - ./aws/install @@ -209,8 +224,16 @@ pipelines: fi if [ "${HAS_LOCAL_JAR}" = "true" ]; then echo "INFO: Artefacto JAR encontrado localmente. Procediendo con instalaciΓ³n en servidor." + mkdir -p ~/.ssh echo "${SSH_PRIVATE_KEY_THOTH}" > ~/.ssh/sacc4_key chmod 600 ~/.ssh/sacc4_key + eval "$(ssh-agent -s)" + expect -c " + spawn ssh-add ~/.ssh/sacc4_key + expect \"Enter passphrase\" + send \"${SSH_PASSPHRASE_THOTH}\r\" + expect eof + " ssh -p "22" \ -i ~/.ssh/sacc4_key \ -o StrictHostKeyChecking=no \ @@ -226,14 +249,23 @@ pipelines: oidc: true script: - set -euo pipefail - - apt-get update -y && apt-get install -y curl unzip + - apt-get update -y && apt-get install -y curl unzip expect - curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" - unzip -q awscliv2.zip - ./aws/install - aws --version - source scripts/aws-oidc-setup.sh dev + - mkdir -p ~/.ssh - echo "${SSH_PRIVATE_KEY_THOTH}" > ~/.ssh/sacc4_key - chmod 600 ~/.ssh/sacc4_key + - eval "$(ssh-agent -s)" + - | + expect -c " + spawn ssh-add ~/.ssh/sacc4_key + expect \"Enter passphrase\" + send \"${SSH_PASSPHRASE_THOTH}\r\" + expect eof + " - | ssh -p "22" \ -i ~/.ssh/sacc4_key \ diff --git a/docs/VALIDACION_CUENTA_AWS.md b/docs/VALIDACION_CUENTA_AWS.md new file mode 100644 index 0000000..2bd6264 --- /dev/null +++ b/docs/VALIDACION_CUENTA_AWS.md @@ -0,0 +1,112 @@ +# ValidaciΓ³n de Recursos AWS - Cuenta 668889063715 + +**Fecha:** Abril 2026 +**Cuenta:** 668889063715 +**RegiΓ³n Principal:** mx-central-1 +**Entorno:** SOLO DESARROLLO (DEV) + +--- + +## Resumen Ejecutivo + +| ValidaciΓ³n | Estado | +|-----------|--------| +| Solo recursos DEV | βœ… CONFIRMADO | +| Sin recursos PROD | βœ… CONFIRMADO | +| Sin duplicaciΓ³n entre regiones | βœ… CONFIRMADO | +| Costos acordes a DEV | βœ… CONFIRMADO | + +--- + +## Inventario Completo + +### 1. EC2 (Instancias) + +| ID | Nombre | Tipo | Estado | IP PΓΊblica | IP Privada | +|----|--------|------|--------|------------|------------| +| i-044018f36de1020a8 | proyectosacc-api-dev | t3.small | running | 78.12.135.184 | 10.1.0.20 | + +**Total:** 1 instancia (solo DEV) + +### 2. RDS (Bases de Datos) + +| ID | Motor | Estado | Base de Datos | Clase | PΓΊblico | +|----|-------|--------|---------------|-------|---------| +| proyectosacc-db-dev | mariadb | available | ccsoft_sacc4 | db.t3.micro | No | + +**Total:** 1 base de datos (solo DEV) + +### 3. S3 (Buckets) + +| Bucket | Uso | +|--------|-----| +| ccsoft-proyectosacc-artifacts-dev | Artefactos de compilaciΓ³n | +| ccsoft-proyectosacc-frontend-dev | Frontend compilado | +| ccsoft-terraform-state | Estado de Terraform | + +**Total:** 3 buckets (todos DEV) + +### 4. CloudFront (CDN) + +| ID | Dominio | Estado | +|----|---------|--------| +| E2EJ7237VFEJAR | d3donfm7ov3eyb.cloudfront.net | Deployed | + +**Total:** 1 distribuciΓ³n (DEV) + +### 5. VPC (Redes) + +| ID | Nombre | CIDR | Default | +|----|--------|------|---------| +| vpc-0fefbaa0848a316dd | proyectosacc-vpc-dev | 10.1.0.0/16 | No | +| vpc-04f5f7cce6ead6c45 | - | 172.31.0.0/16 | SΓ­ (default) | + +### 6. Route53 (DNS) + +| Zona | Dominio | Privada | +|------|---------|---------| +| Z00862912V7J2IBIAQU9Z | dev-sacc.ccsoft.mx | No | + +### 7. Security Groups + +| ID | Nombre | DescripciΓ³n | +|----|--------|-------------| +| sg-0052f147c98bb1904 | proyectosacc-ec2-api | API backend | +| sg-0b4190c4cec1ad2f5 | proyectosacc-rds | RDS MariaDB (acceso solo desde 10.1.0.20/32) | + +--- + +## Validaciones de Seguridad + +| VerificaciΓ³n | Estado | +|-------------|--------| +| BΓΊsqueda de recursos con tag "prod" | ❌ No encontrados | +| BΓΊsqueda de recursos con tag "production" | ❌ No encontrados | +| Buckets con nombre "prod" o "production" | ❌ No encontrados | +| Instancias EC2 en otras regiones | ❌ No encontradas | +| Bases de datos RDS en otras regiones | ❌ No encontradas | + +--- + +## Costos Estimados + +**Promedio diario:** ~$2.43 USD +**Estimado mensual:** ~$73 USD + +**Desglose aproximado:** +- EC2 t3.small: ~$15/mes +- RDS db.t3.micro: ~$13/mes +- S3 + CloudFront + Data Transfer: ~$45/mes + +--- + +## ConclusiΓ³n + +βœ… **La cuenta 668889063715 contiene ÚNICAMENTE recursos de desarrollo (DEV).** + +- No hay servicios de producciΓ³n duplicados +- No hay recursos en otras regiones +- Todos los recursos estΓ‘n correctamente etiquetados como DEV +- Los costos son consistentes con un entorno de desarrollo + +**RecomendaciΓ³n:** Mantener esta cuenta exclusivamente para desarrollo y no desplegar recursos de producciΓ³n aquΓ­. diff --git a/scripts/validar_conexion_rds.sh b/scripts/validar_conexion_rds.sh new file mode 100644 index 0000000..2f101ff --- /dev/null +++ b/scripts/validar_conexion_rds.sh @@ -0,0 +1,363 @@ +#!/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}"