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
This commit is contained in:
Jenkins CI
2026-06-03 04:39:01 +00:00
commit 71be2abd2e
27 changed files with 6424 additions and 0 deletions
+488
View File
@@ -0,0 +1,488 @@
#!/bin/bash
# =============================================================================
# SACC v4 - Script de Creacion de Entorno TEST
# =============================================================================
# Cuenta AWS: 668889063715
# Region: mx-central-1
#
# Este script:
# 1. Valida prerequisitos (AWS CLI, Terraform, credenciales)
# 2. Verifica que no existan recursos con conflictos de nombres
# 3. Crea backend S3/DynamoDB para estado Terraform
# 4. Ejecuta terraform init/plan/apply
# 5. Genera inventario Ansible
# 6. Ejecuta playbooks de Ansible
# 7. Verifica health checks
#
# USO:
# export AWS_ACCESS_KEY_ID=...
# export AWS_SECRET_ACCESS_KEY=...
# export AWS_SESSION_TOKEN=...
# export AWS_DEFAULT_REGION=mx-central-1
# ./create-test-environment.sh
#
# IMPORTANTE: NO ejecutar en produccion
# =============================================================================
set -euo pipefail
# Colores para output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# =============================================================================
# CONFIGURACION
# =============================================================================
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
TERRAFORM_DIR="$PROJECT_ROOT/terraform/environments/test"
ANSIBLE_DIR="$PROJECT_ROOT/ansible"
LOG_FILE="$PROJECT_ROOT/logs/create-test-$(date +%Y%m%d-%H%M%S).log"
ACCOUNT_ID="668889063715"
REGION="mx-central-1"
# Crear directorio de logs
mkdir -p "$(dirname "$LOG_FILE")"
# =============================================================================
# FUNCIONES DE UTILIDAD
# =============================================================================
log() {
echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')] INFO:${NC} $1" | tee -a "$LOG_FILE"
}
warn() {
echo -e "${YELLOW}[$(date '+%Y-%m-%d %H:%M:%S')] WARN:${NC} $1" | tee -a "$LOG_FILE"
}
error() {
echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')] ERROR:${NC} $1" | tee -a "$LOG_FILE"
exit 1
}
info() {
echo -e "${BLUE}[$(date '+%Y-%m-%d %H:%M:%S')] INFO:${NC} $1" | tee -a "$LOG_FILE"
}
# =============================================================================
# PASO 1: VALIDAR PREREQUISITOS
# =============================================================================
validate_prerequisites() {
info "========================================"
info "PASO 1: Validando prerequisitos"
info "========================================"
# Validar AWS CLI
if ! command -v aws &> /dev/null; then
error "AWS CLI no esta instalado. Instalar desde: https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html"
fi
log "AWS CLI: $(aws --version | head -1)"
# Validar Terraform
if ! command -v terraform &> /dev/null; then
error "Terraform no esta instalado. Instalar desde: https://developer.hashicorp.com/terraform/downloads"
fi
log "Terraform: $(terraform version | head -1)"
# Validar Ansible
if ! command -v ansible-playbook &> /dev/null; then
warn "Ansible no esta instalado. Se omitira el paso de Ansible."
ANSIBLE_AVAILABLE=false
else
log "Ansible: $(ansible-playbook --version | head -1)"
ANSIBLE_AVAILABLE=true
fi
# Validar credenciales AWS
info "Verificando credenciales AWS..."
if ! aws sts get-caller-identity &> /dev/null; then
error "No se pueden validar las credenciales AWS. Asegurate de configurar:\n export AWS_ACCESS_KEY_ID=...\n export AWS_SECRET_ACCESS_KEY=...\n export AWS_SESSION_TOKEN=...\n export AWS_DEFAULT_REGION=mx-central-1"
fi
local caller_identity
caller_identity=$(aws sts get-caller-identity --output json)
local account_id
account_id=$(echo "$caller_identity" | jq -r '.Account')
local arn
arn=$(echo "$caller_identity" | jq -r '.Arn')
if [ "$account_id" != "$ACCOUNT_ID" ]; then
error "Cuenta AWS incorrecta. Esperada: $ACCOUNT_ID, Actual: $account_id"
fi
log "Credenciales AWS validas"
log " Cuenta: $account_id"
log " ARN: $arn"
log " Region: $REGION"
# Validar region
local current_region
current_region=$(aws configure get region 2>/dev/null || echo "$AWS_DEFAULT_REGION")
if [ "$current_region" != "$REGION" ]; then
warn "Region actual ($current_region) diferente de la esperada ($REGION)"
warn "Estableciendo AWS_DEFAULT_REGION=$REGION"
export AWS_DEFAULT_REGION="$REGION"
fi
# Validar archivo de variables
if [ ! -f "$TERRAFORM_DIR/terraform.tfvars" ]; then
error "No existe $TERRAFORM_DIR/terraform.tfvars\nCopiar desde terraform.tfvars.example y completar los valores."
fi
log "Archivo terraform.tfvars encontrado"
# Validar llaves SSH
if [ ! -f "$HOME/.ssh/sacc4-test-key.pem" ]; then
warn "No existe ~/.ssh/sacc4-test-key.pem"
warn "Generar con: ssh-keygen -t ed25519 -f ~/.ssh/sacc4-test-key -C 'sacc4-test'"
warn "Subir la llave publica a AWS: aws ec2 import-key-pair ..."
fi
}
# =============================================================================
# PASO 2: VERIFICAR CONFLICTOS DE NOMBRES
# =============================================================================
check_conflicts() {
info "========================================"
info "PASO 2: Verificando conflictos de nombres"
info "========================================"
local conflicts_found=0
# Verificar bucket S3
local bucket_name
bucket_name=$(grep "frontend_bucket_name" "$TERRAFORM_DIR/terraform.tfvars" | cut -d'=' -f2 | tr -d ' "')
log "Verificando bucket S3: $bucket_name"
if aws s3api head-bucket --bucket "$bucket_name" 2>/dev/null; then
warn "Bucket S3 '$bucket_name' ya existe"
conflicts_found=$((conflicts_found + 1))
else
log "Bucket S3 disponible"
fi
# Verificar instancia RDS
local rds_id="sacc4-test-db-prod"
log "Verificando RDS: $rds_id"
if aws rds describe-db-instances --db-instance-identifier "$rds_id" 2>/dev/null; then
warn "RDS '$rds_id' ya existe"
conflicts_found=$((conflicts_found + 1))
else
log "RDS disponible"
fi
# Verificar VPC con mismo CIDR
local vpc_cidr
vpc_cidr=$(grep "vpc_cidr" "$TERRAFORM_DIR/terraform.tfvars" | head -1 | cut -d'=' -f2 | tr -d ' "')
log "Verificando VPC CIDR: $vpc_cidr"
local existing_vpcs
existing_vpcs=$(aws ec2 describe-vpcs --filters "Name=cidr,Values=$vpc_cidr" --query 'Vpcs[*].VpcId' --output text)
if [ -n "$existing_vpcs" ] && [ "$existing_vpcs" != "None" ]; then
warn "VPC con CIDR $vpc_cidr ya existe: $existing_vpcs"
conflicts_found=$((conflicts_found + 1))
else
log "VPC CIDR disponible"
fi
# Verificar tabla DynamoDB para locks
local dynamo_table="sacc4-terraform-locks-test-668889063715"
log "Verificando DynamoDB: $dynamo_table"
if aws dynamodb describe-table --table-name "$dynamo_table" 2>/dev/null; then
warn "Tabla DynamoDB '$dynamo_table' ya existe"
conflicts_found=$((conflicts_found + 1))
else
log "Tabla DynamoDB disponible"
fi
# Verificar bucket de estado Terraform
local state_bucket="sacc4-terraform-state-test-668889063715"
log "Verificando bucket de estado: $state_bucket"
if aws s3api head-bucket --bucket "$state_bucket" 2>/dev/null; then
warn "Bucket de estado '$state_bucket' ya existe"
conflicts_found=$((conflicts_found + 1))
else
log "Bucket de estado disponible"
fi
if [ $conflicts_found -gt 0 ]; then
warn "Se encontraron $conflicts_found conflictos. Revisar antes de continuar."
read -p "Continuar de todos modos? (yes/no): " confirm
if [ "$confirm" != "yes" ]; then
error "Abortado por el usuario"
fi
else
log "No se encontraron conflictos"
fi
}
# =============================================================================
# PASO 3: CREAR BACKEND TERRAFORM (S3 + DynamoDB)
# =============================================================================
create_backend() {
info "========================================"
info "PASO 3: Creando backend para estado Terraform"
info "========================================"
local state_bucket="sacc4-terraform-state-test-668889063715"
local dynamo_table="sacc4-terraform-locks-test-668889063715"
# Crear bucket S3
log "Creando bucket S3: $state_bucket"
if ! aws s3api head-bucket --bucket "$state_bucket" 2>/dev/null; then
aws s3api create-bucket \
--bucket "$state_bucket" \
--region "$REGION" \
--create-bucket-configuration LocationConstraint="$REGION"
log "Bucket creado"
else
log "Bucket ya existe"
fi
# Habilitar versionamiento
log "Habilitando versionamiento en bucket"
aws s3api put-bucket-versioning \
--bucket "$state_bucket" \
--versioning-configuration Status=Enabled
# Encriptacion
log "Configurando encriptacion del bucket"
aws s3api put-bucket-encryption \
--bucket "$state_bucket" \
--server-side-encryption-configuration '{
"Rules": [{"ApplyServerSideEncryptionByDefault": {"SSEAlgorithm": "AES256"}}]
}'
# Crear tabla DynamoDB
log "Creando tabla DynamoDB: $dynamo_table"
if ! aws dynamodb describe-table --table-name "$dynamo_table" 2>/dev/null; then
aws dynamodb create-table \
--table-name "$dynamo_table" \
--attribute-definitions AttributeName=LockID,AttributeType=S \
--key-schema AttributeName=LockID,KeyType=HASH \
--billing-mode PAY_PER_REQUEST \
--region "$REGION"
log "Tabla DynamoDB creada"
else
log "Tabla DynamoDB ya existe"
fi
}
# =============================================================================
# PASO 4: TERRAFORM INIT / PLAN / APPLY
# =============================================================================
run_terraform() {
info "========================================"
info "PASO 4: Ejecutando Terraform"
info "========================================"
cd "$TERRAFORM_DIR"
log "Inicializando Terraform..."
terraform init
log "Ejecutando terraform plan..."
terraform plan -out=tfplan -var-file=terraform.tfvars
info "Revisar el plan anterior. Se crearan los recursos listados arriba."
read -p "Aplicar cambios? (yes/no): " confirm
if [ "$confirm" != "yes" ]; then
error "Abortado por el usuario"
fi
log "Aplicando infraestructura (esto puede tomar 10-15 minutos)..."
terraform apply tfplan
log "Terraform apply completado"
}
# =============================================================================
# PASO 5: GENERAR INVENTARIO ANSIBLE
# =============================================================================
generate_ansible_inventory() {
info "========================================"
info "PASO 5: Generando inventario Ansible"
info "========================================"
cd "$TERRAFORM_DIR"
local ec2_ip
ec2_ip=$(terraform output -raw ec2_public_ip)
local rds_endpoint
rds_endpoint=$(terraform output -raw rds_endpoint)
local s3_bucket
s3_bucket=$(terraform output -raw frontend_bucket_name)
mkdir -p "$ANSIBLE_DIR/inventory"
cat > "$ANSIBLE_DIR/inventory/test.ini" << EOF
[sacc4-test]
$ec2_ip ansible_user=ubuntu ansible_ssh_private_key_file=~/.ssh/sacc4-test-key.pem ansible_python_interpreter=/usr/bin/python3
[sacc4-test:vars]
environment=test
db_endpoint=$rds_endpoint
s3_bucket=$s3_bucket
EOF
log "Inventario Ansible generado: $ANSIBLE_DIR/inventory/test.ini"
cat "$ANSIBLE_DIR/inventory/test.ini"
}
# =============================================================================
# PASO 6: EJECUTAR ANSIBLE
# =============================================================================
run_ansible() {
info "========================================"
info "PASO 6: Configurando servidor con Ansible"
info "========================================"
if [ "$ANSIBLE_AVAILABLE" != "true" ]; then
warn "Ansible no disponible. Omitiendo configuracion."
info "Para ejecutar manualmente despues:"
info " cd $ANSIBLE_DIR"
info " ansible-playbook -i inventory/test.ini playbooks/site.yml"
return
fi
cd "$ANSIBLE_DIR"
log "Ejecutando playbook Ansible..."
ansible-playbook -i inventory/test.ini playbooks/site.yml
log "Ansible completado"
}
# =============================================================================
# PASO 7: VERIFICAR HEALTH CHECKS
# =============================================================================
verify_health_checks() {
info "========================================"
info "PASO 7: Verificando health checks"
info "========================================"
cd "$TERRAFORM_DIR"
local ec2_ip
ec2_ip=$(terraform output -raw ec2_public_ip)
log "Verificando conectividad SSH..."
if ssh -i ~/.ssh/sacc4-test-key.pem -o StrictHostKeyChecking=no -o ConnectTimeout=10 ubuntu@"$ec2_ip" "echo 'OK'" > /dev/null 2>&1; then
log "SSH: OK"
else
warn "SSH: No responde (la instancia puede estar inicializando)"
fi
log "Verificando Nginx..."
if ssh -i ~/.ssh/sacc4-test-key.pem -o StrictHostKeyChecking=no ubuntu@"$ec2_ip" "sudo systemctl is-active nginx" 2>/dev/null; then
log "Nginx: Activo"
else
warn "Nginx: No activo (esperar a que Ansible termine)"
fi
log "Verificando servicios en puertos 8080-8085..."
for port in 8080 8081 8082 8083 8084 8085; do
if ssh -i ~/.ssh/sacc4-test-key.pem -o StrictHostKeyChecking=no ubuntu@"$ec2_ip" "curl -s -o /dev/null -w '%{http_code}' http://localhost:$port/actuator/health 2>/dev/null || echo '000'" 2>/dev/null | grep -q "200"; then
log "Puerto $port: OK"
else
warn "Puerto $port: No responde (esperar despliegue de JARs)"
fi
done
log "Verificando RDS..."
local rds_endpoint
rds_endpoint=$(terraform output -raw rds_endpoint)
if ssh -i ~/.ssh/sacc4-test-key.pem -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: Conexion exitosa"
else
warn "RDS: No se pudo conectar (verificar credenciales y security groups)"
fi
log "Verificando S3..."
local s3_bucket
s3_bucket=$(terraform output -raw frontend_bucket_name)
if aws s3 ls "s3://$s3_bucket" >/dev/null 2>&1; then
log "S3: Bucket accesible"
else
warn "S3: No se pudo acceder al bucket"
fi
}
# =============================================================================
# PASO 8: MOSTRAR RESUMEN
# =============================================================================
show_summary() {
info "========================================"
info "RESUMEN DEL DESPLIEGUE"
info "========================================"
cd "$TERRAFORM_DIR"
info "Outputs de Terraform:"
terraform output
info ""
info "Recursos creados en cuenta $ACCOUNT_ID:"
info " VPC: $(terraform output -raw vpc_id 2>/dev/null || echo 'N/A')"
info " EC2: $(terraform output -raw ec2_public_ip 2>/dev/null || echo 'N/A')"
info " RDS: $(terraform output -raw rds_endpoint 2>/dev/null || echo 'N/A')"
info " S3: $(terraform output -raw frontend_bucket_name 2>/dev/null || echo 'N/A')"
info " CloudFront: $(terraform output -raw cloudfront_domain_name 2>/dev/null || echo 'N/A')"
info ""
info "Proximos pasos:"
info " 1. Desplegar JARs de microservicios a /opt/sacc4/*/current/"
info " 2. Configurar certificado SSL (Let's Encrypt o ACM)"
info " 3. Verificar DNS: $(terraform output -raw api_subdomain 2>/dev/null || echo 'N/A')"
info " 4. Ejecutar: $SCRIPT_DIR/validate-environment.sh"
info ""
info "Para destruir el entorno:"
info " $SCRIPT_DIR/destroy-test-environment.sh"
}
# =============================================================================
# MAIN
# =============================================================================
main() {
info "========================================"
info "SACC v4 - Creacion de Entorno TEST"
info "Cuenta: $ACCOUNT_ID"
info "Region: $REGION"
info "========================================"
info ""
info "IMPORTANTE:"
info " - Este script creara recursos AWS que generan costos"
info " - Verificar que las credenciales sean de la cuenta correcta"
info " - No ejecutar en produccion"
info ""
read -p "Continuar? (yes/no): " confirm
if [ "$confirm" != "yes" ]; then
error "Abortado por el usuario"
fi
validate_prerequisites
check_conflicts
create_backend
run_terraform
generate_ansible_inventory
run_ansible
verify_health_checks
show_summary
log "Proceso completado exitosamente"
log "Log guardado en: $LOG_FILE"
}
main "$@"
+483
View File
@@ -0,0 +1,483 @@
#!/bin/bash
# =============================================================================
# SACC v4 - Script de Destruccion de Entorno TEST
# =============================================================================
# Destruye de forma SEGURA el entorno de pruebas en cuenta 668889063715
#
# Este script:
# 1. Pide confirmacion multiple
# 2. Realiza backup de datos RDS
# 3. Destruye recursos Terraform
# 4. Limpia S3 (opcional)
# 5. Muestra resumen de lo destruido
#
# USO:
# export AWS_ACCESS_KEY_ID=...
# export AWS_SECRET_ACCESS_KEY=...
# export AWS_SESSION_TOKEN=...
# export AWS_DEFAULT_REGION=mx-central-1
# ./destroy-test-environment.sh [opciones]
#
# OPCIONES:
# --force Omitir confirmaciones (USAR CON PRECAUCION)
# --skip-rds-backup Omitir backup de RDS
# --delete-s3 Eliminar contenido de S3 antes de destruir
# --keep-state No eliminar bucket de estado Terraform
# =============================================================================
set -euo pipefail
# Colores
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
BOLD='\033[1m'
NC='\033[0m'
# =============================================================================
# CONFIGURACION
# =============================================================================
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
TERRAFORM_DIR="$PROJECT_ROOT/terraform/environments/test"
BACKUP_DIR="$PROJECT_ROOT/backups/rds-$(date +%Y%m%d-%H%M%S)"
LOG_FILE="$PROJECT_ROOT/logs/destroy-$(date +%Y%m%d-%H%M%S).log"
ACCOUNT_ID="668889063715"
REGION="mx-central-1"
mkdir -p "$(dirname "$LOG_FILE")"
# Flags
FORCE=false
SKIP_RDS_BACKUP=false
DELETE_S3=false
KEEP_STATE=false
# =============================================================================
# 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')] ERROR:${NC} $1" | tee -a "$LOG_FILE"
}
info() {
echo -e "${BLUE}[$(date '+%H:%M:%S')] INFO:${NC} $1" | tee -a "$LOG_FILE"
}
fatal() {
echo -e "${RED}${BOLD}[$(date '+%H:%M:%S')] FATAL:${NC} $1" | tee -a "$LOG_FILE"
exit 1
}
# =============================================================================
# PARSEAR ARGUMENTOS
# =============================================================================
parse_args() {
while [ $# -gt 0 ]; do
case "$1" in
--force)
FORCE=true
warn "Modo FORZADO activado - Se omitiran confirmaciones"
;;
--skip-rds-backup)
SKIP_RDS_BACKUP=true
warn "Se omitira backup de RDS"
;;
--delete-s3)
DELETE_S3=true
info "Se eliminara contenido de S3"
;;
--keep-state)
KEEP_STATE=true
info "Se conservara bucket de estado Terraform"
;;
--help)
echo "Uso: $0 [opciones]"
echo ""
echo "Opciones:"
echo " --force Omitir confirmaciones (USAR CON PRECAUCION)"
echo " --skip-rds-backup Omitir backup de RDS"
echo " --delete-s3 Eliminar contenido de S3 antes de destruir"
echo " --keep-state No eliminar bucket de estado Terraform"
echo " --help Mostrar esta ayuda"
exit 0
;;
*)
echo "Opcion desconocida: $1"
exit 1
;;
esac
shift
done
}
# =============================================================================
# VALIDAR PREREQUISITOS
# =============================================================================
validate() {
info "========================================"
info "Validando prerequisitos"
info "========================================"
if ! command -v aws &> /dev/null; then
fatal "AWS CLI no esta instalado"
fi
if ! command -v terraform &> /dev/null; then
fatal "Terraform no esta instalado"
fi
# Verificar credenciales
local current_account
current_account=$(aws sts get-caller-identity --query 'Account' --output text)
if [ "$current_account" != "$ACCOUNT_ID" ]; then
fatal "Cuenta AWS incorrecta. Esperada: $ACCOUNT_ID, Actual: $current_account"
fi
log "Cuenta AWS validada: $current_account"
# Verificar estado de Terraform
if [ ! -f "$TERRAFORM_DIR/terraform.tfstate" ] && [ ! -d "$TERRAFORM_DIR/.terraform" ]; then
fatal "No existe estado de Terraform en $TERRAFORM_DIR"
fi
}
# =============================================================================
# MOSTRAR RECURSOS A DESTRUIR
# =============================================================================
show_resources() {
info "========================================"
info "Recursos que seran destruidos"
info "========================================"
cd "$TERRAFORM_DIR"
info "Ejecutando terraform plan -destroy..."
terraform plan -destroy -var-file=terraform.tfvars -out=destroy.plan
info ""
info "Revisa el plan de destruccion mostrado arriba."
info ""
}
# =============================================================================
# CONFIRMACIONES
# =============================================================================
confirm_destruction() {
if [ "$FORCE" == "true" ]; then
warn "Modo forzado: Omitiendo confirmaciones"
return 0
fi
echo ""
echo -e "${RED}${BOLD}ATENCION: ESTA ACCION ES IRREVERSIBLE${NC}"
echo -e "${RED}Se destruiran todos los recursos del entorno TEST${NC}"
echo ""
echo "Recursos afectados:"
echo " - Instancia EC2 (con Elastic IP)"
echo " - Base de datos RDS (con backups automaticos)"
echo " - Bucket S3 (frontend)"
echo " - Distribucion CloudFront"
echo " - Funciones Lambda y EventBridge"
echo " - Security Groups, VPC, Subnets"
echo " - Registros Route53"
echo ""
read -p "Escribe 'DESTRUIR' para confirmar: " confirm1
if [ "$confirm1" != "DESTRUIR" ]; then
fatal "Confirmacion incorrecta. Abortando."
fi
read -p "Estas ABSOLUTAMENTE SEGURO? Escribe 'SI': " confirm2
if [ "$confirm2" != "SI" ]; then
fatal "Confirmacion incorrecta. Abortando."
fi
log "Confirmacion recibida. Procediendo con la destruccion."
}
# =============================================================================
# BACKUP DE RDS
# =============================================================================
backup_rds() {
if [ "$SKIP_RDS_BACKUP" == "true" ]; then
warn "Omitiendo backup de RDS (--skip-rds-backup)"
return 0
fi
info "========================================"
info "Realizando backup de RDS"
info "========================================"
cd "$TERRAFORM_DIR"
local rds_endpoint
rds_endpoint=$(terraform output -raw rds_endpoint 2>/dev/null || echo "")
local db_name
db_name=$(terraform output -raw rds_db_name 2>/dev/null || echo "")
if [ -z "$rds_endpoint" ]; then
warn "No se pudo obtener endpoint RDS. Omitiendo backup."
return 1
fi
mkdir -p "$BACKUP_DIR"
log "RDS Endpoint: $rds_endpoint"
log "Base de datos: $db_name"
log "Directorio de backup: $BACKUP_DIR"
# Crear snapshot final
local snapshot_id="sacc4-test-final-$(date +%Y%m%d-%H%M%S)"
local rds_instance_id="sacc4-test-db-prod"
log "Creando snapshot final: $snapshot_id"
aws rds create-db-snapshot \
--db-instance-identifier "$rds_instance_id" \
--db-snapshot-identifier "$snapshot_id" \
--region "$REGION"
log "Esperando que el snapshot se complete..."
aws rds wait db-snapshot-available \
--db-snapshot-identifier "$snapshot_id" \
--region "$REGION"
log "Snapshot creado exitosamente: $snapshot_id"
echo "$snapshot_id" > "$BACKUP_DIR/snapshot-id.txt"
# Intentar dump SQL (si tenemos acceso)
local ec2_ip
ec2_ip=$(terraform output -raw ec2_public_ip 2>/dev/null || echo "")
local ssh_key="$HOME/.ssh/sacc4-test-key.pem"
if [ -n "$ec2_ip" ] && [ -f "$ssh_key" ]; then
log "Intentando crear dump SQL desde EC2..."
if ssh -i "$ssh_key" -o StrictHostKeyChecking=no ubuntu@"$ec2_ip" "mysqldump -h $rds_endpoint -u sacc_app_user -p'$db_name' --all-databases > /tmp/sacc4-test-backup.sql 2>/dev/null" 2>/dev/null; then
scp -i "$ssh_key" -o StrictHostKeyChecking=no "ubuntu@$ec2_ip:/tmp/sacc4-test-backup.sql" "$BACKUP_DIR/"
log "Dump SQL guardado en: $BACKUP_DIR/sacc4-test-backup.sql"
else
warn "No se pudo crear dump SQL (credenciales no disponibles)"
fi
fi
log "Backup completado en: $BACKUP_DIR"
}
# =============================================================================
# LIMPIAR S3
# =============================================================================
cleanup_s3() {
if [ "$DELETE_S3" != "true" ]; then
info "Omitiendo limpieza de S3 (usar --delete-s3 para eliminar)"
return 0
fi
info "========================================"
info "Limpiando bucket S3"
info "========================================"
cd "$TERRAFORM_DIR"
local bucket_name
bucket_name=$(terraform output -raw frontend_bucket_name 2>/dev/null || echo "")
if [ -z "$bucket_name" ]; then
warn "No se pudo obtener nombre del bucket S3"
return 1
fi
log "Bucket a limpiar: $bucket_name"
# Verificar si tiene versionamiento
local versioning
versioning=$(aws s3api get-bucket-versioning --bucket "$bucket_name" --query 'Status' --output text 2>/dev/null || echo "Disabled")
if [ "$versioning" == "Enabled" ]; then
warn "Bucket tiene versionamiento habilitado. Eliminando todas las versiones..."
# Eliminar todas las versiones (incluyendo delete markers)
aws s3api list-object-versions --bucket "$bucket_name" --query 'Versions[].{Key:Key,VersionId:VersionId}' --output json | \
jq -c '.[]' | while read -r obj; do
key=$(echo "$obj" | jq -r '.Key')
version=$(echo "$obj" | jq -r '.VersionId')
aws s3api delete-object --bucket "$bucket_name" --key "$key" --version-id "$version" > /dev/null
done
fi
# Vaciar bucket
log "Vaciando bucket..."
aws s3 rm "s3://$bucket_name" --recursive
log "Bucket $bucket_name vaciado"
}
# =============================================================================
# DESTRUIR CON TERRAFORM
# =============================================================================
destroy_terraform() {
info "========================================"
info "Destruyendo recursos con Terraform"
info "========================================"
cd "$TERRAFORM_DIR"
if [ "$FORCE" == "true" ]; then
terraform destroy -auto-approve -var-file=terraform.tfvars
else
terraform destroy -var-file=terraform.tfvars
fi
log "Terraform destroy completado"
}
# =============================================================================
# LIMPIAR ESTADO TERRAFORM
# =============================================================================
cleanup_terraform_state() {
if [ "$KEEP_STATE" == "true" ]; then
info "Conservando bucket de estado Terraform (--keep-state)"
return 0
fi
info "========================================"
info "Limpiando recursos de estado Terraform"
info "========================================"
local state_bucket="sacc4-terraform-state-test-668889063715"
local dynamo_table="sacc4-terraform-locks-test-668889063715"
# Preguntar antes de eliminar
if [ "$FORCE" != "true" ]; then
read -p "Eliminar bucket de estado S3 y tabla DynamoDB? (yes/no): " confirm
if [ "$confirm" != "yes" ]; then
warn "Conservando recursos de estado"
return 0
fi
fi
# Eliminar contenido del bucket primero
log "Vaciando bucket de estado: $state_bucket"
aws s3 rm "s3://$state_bucket" --recursive 2>/dev/null || true
# Eliminar bucket
log "Eliminando bucket: $state_bucket"
aws s3api delete-bucket --bucket "$state_bucket" --region "$REGION" 2>/dev/null || warn "No se pudo eliminar bucket"
# Eliminar tabla DynamoDB
log "Eliminando tabla DynamoDB: $dynamo_table"
aws dynamodb delete-table --table-name "$dynamo_table" --region "$REGION" 2>/dev/null || warn "No se pudo eliminar tabla"
log "Recursos de estado eliminados"
}
# =============================================================================
# VERIFICAR DESTRUCCION
# =============================================================================
verify_destruction() {
info "========================================"
info "Verificando destruccion"
info "========================================"
cd "$TERRAFORM_DIR"
local vpc_id
vpc_id=$(terraform output -raw vpc_id 2>/dev/null || echo "")
if [ -n "$vpc_id" ]; then
if aws ec2 describe-vpcs --vpc-ids "$vpc_id" >/dev/null 2>&1; then
warn "VPC $vpc_id aun existe"
else
log "VPC eliminada correctamente"
fi
fi
# Verificar EC2
local ec2_ip
ec2_ip=$(terraform output -raw ec2_public_ip 2>/dev/null || echo "")
if [ -n "$ec2_ip" ]; then
if ping -c 1 -W 2 "$ec2_ip" >/dev/null 2>&1; then
warn "EC2 $ec2_ip aun responde a ping"
else
log "EC2 no responde (esperado)"
fi
fi
}
# =============================================================================
# RESUMEN
# =============================================================================
show_summary() {
info "========================================"
info "RESUMEN DE DESTRUCCION"
info "========================================"
log "Entorno TEST destruido exitosamente"
info ""
info "Acciones realizadas:"
if [ "$SKIP_RDS_BACKUP" != "true" ]; then
info " [OK] Backup de RDS guardado en: $BACKUP_DIR"
fi
if [ "$DELETE_S3" == "true" ]; then
info " [OK] Contenido de S3 eliminado"
fi
info " [OK] Recursos de infraestructura destruidos"
if [ "$KEEP_STATE" != "true" ]; then
info " [OK] Estado Terraform eliminado"
fi
info ""
info "Costos: La destruccion de recursos detiene la generacion de cargos."
info "Nota: Los snapshots de RDS y logs de CloudWatch pueden generar costos menores."
info ""
info "Log completo: $LOG_FILE"
}
# =============================================================================
# MAIN
# =============================================================================
main() {
parse_args "$@"
echo -e "${RED}${BOLD}"
echo "========================================"
echo "SACC v4 - Destruccion de Entorno TEST"
echo "========================================"
echo -e "${NC}"
echo "Cuenta: $ACCOUNT_ID"
echo "Region: $REGION"
echo ""
echo -e "${RED}ADVERTENCIA: Esta accion destruira todos los recursos${NC}"
validate
show_resources
confirm_destruction
backup_rds
cleanup_s3
destroy_terraform
cleanup_terraform_state
verify_destruction
show_summary
}
main "$@"
+533
View File
@@ -0,0 +1,533 @@
#!/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 "$@"