19 Commits

Author SHA1 Message Date
Evert Daniel Romero Garrido aaa2c06c30 feat(terraform): Add lifecycle rules and import blocks for existing resources
Lifecycle Rules:
- Add prevent_destroy = true to all 32+ resources
- Add ignore_changes = [tags] to prevent tag drift from causing recreation
- Add ignore_changes = [tags, user_data, ami, iam_instance_profile] for EC2
- Preserve existing create_before_destroy for security groups and ACM

Import Blocks (orphaned resources):
- Lambda: sacc4-stop-instances
- Lambda: sacc4-start-instances
- EventBridge: sacc4-stop-instances-schedule
- EventBridge: sacc4-start-instances-schedule

Data Sources:
- aws_instances.existing_api (detect EC2 duplicates)
- aws_db_instance.existing (detect RDS duplicates)
- aws_nat_gateways.existing (detect NAT GW duplicates)
- aws_cloudfront_distribution.existing (detect CloudFront duplicates)

Variables:
- db_identifier: for RDS duplicate detection
- cloudfront_distribution_id: for CloudFront duplicate detection

Validation Results:
- terraform validate: PASSED
- terraform plan: 0 to add, 1 to change, 0 to destroy
- No resources marked for recreation

Orphan EIP detected:
- eipalloc-0bdf9c47a80885c7a (78.13.177.201) unattached
- Requires manual cleanup or investigation

Refs: AWS Resource Validation - May 2026
2026-05-07 11:12:24 -06:00
Evert Daniel Romero Garrido 557feb02e0 feat(terraform): agregar lifecycle prevent_destroy a recursos críticos
- VPC: prevent_destroy = true
- EC2: prevent_destroy + ignore_changes ami
- RDS: prevent_destroy = true
- S3 frontend/artifacts: prevent_destroy = true
- Prevenir destrucción accidental de infraestructura PROD
2026-05-07 11:09:55 -06:00
Evert Daniel Romero Garrido 41b2347a33 fix(backend): corregir nombre del bucket S3 de estado y usar use_lockfile
- Bucket correcto: ccsoft-proyectosacc-terraform-state-prod
- Eliminar dynamodb_table deprecado, usar use_lockfile
- Resolver error de region mx-central-1 con Terraform 1.15.2
2026-05-07 10:54:11 -06:00
Evert Daniel Romero Garrido 7e0c764f3f feat(terraform): agregar permisos sudo para thoth y mejorar seguridad
- Configurar permisos sudo completos para usuario thoth:
  * Editar /etc/sacc4/sacc4.env
  * Gestionar servicios api-sacc4-*.service
  * Editar archivos systemd
  * Control total de /opt/sacc4
- Eliminar acceso SSH abierto (0.0.0.0/0)
- Agregar soporte AWS Systems Manager Session Manager
- Actualizar llave SSH a sacc-prod-key-2026
- Preservar tags de scheduling (AutoStart/AutoStop) en EC2 y RDS
- Agregar variable allowed_ssh_cidrs para acceso de emergencia

BREAKING CHANGE: SSH restringido, usar Session Manager como acceso principal
2026-05-07 09:44:44 -06:00
Evert Daniel Romero Garrido defce6933d feat(pipeline): Add SSH key rotation, health checks, and manual approval
Security & Operations Improvements:
- Add step 06_update_ssh_keys to rotate authorized_keys on EC2
  before each deployment, ensuring only current pipeline can access
- Add step 09_health_check with retry logic (12 retries, 10s interval)
  verifying API backend (/actuator/health), CloudFront, and RDS
- Add manual approval (trigger: manual) for production deployment
  with terraform plan saved as artifact (prod.tfplan)
- Document terraform auto-approve policy: dev automatic, prod manual
- Use DEV_DB_HOST and PROD_DB_HOST variables for RDS connectivity checks
- Reorder steps: 7 steps → 9 steps standard CCsoft pipeline

Closes pipeline security gaps and adds post-deploy verification.
2026-04-20 17:47:15 -06:00
Evert Romero 89363827cd chore(terraform): update pipeline_public_key in dev and prod tfvars 2026-04-16 17:03:39 -06:00
Evert Romero 7ea909e854 fix(terraform): permitir SSH desde internet para pipeline Bitbucket 2026-04-16 16:23:51 -06:00
Evert Romero 0cc3e11701 fix(terraform): corregir sintaxis HCL en trust policy OIDC
ForAnyValue:StringEquals debe ir entre comillas dentro de
jsonencode() para que Terraform lo interprete correctamente.
Sin las comillas, terraform init/plan falla con:
Missing attribute separator.
2026-04-16 16:10:43 -06:00
Evert Daniel Romero Garrido ef9fc66171 fix(terraform): corregir OIDC audience para Bitbucket Cloud
Bitbucket Cloud genera tokens JWT con audience fijo:
ari:cloud:bitbucket::workspace/465016f8-d6fb-4ecb-ba6f-2248e938942b

El archivo oidc-bitbucket.tf solo aceptaba sts.amazonaws.com,
lo que causaba InvalidIdentityToken en cada terraform apply.
Ahora el OIDC provider y el rol IAM aceptan ambos audiences
mediante ForAnyValue:StringEquals.
2026-04-16 22:03:30 +00:00
Evert Daniel Romero Garrido 2f4a563f9e fix(terraform): corregir OIDC audience para Bitbucket Cloud
Bitbucket Cloud genera tokens JWT con audience fijo:
ari:cloud:bitbucket::workspace/465016f8-d6fb-4ecb-ba6f-2248e938942b

El archivo oidc-bitbucket.tf solo aceptaba sts.amazonaws.com,
lo que causaba InvalidIdentityToken en cada terraform apply.
Ahora el OIDC provider y el rol IAM aceptan ambos audiences
mediante ForAnyValue:StringEquals.
2026-04-16 21:54:55 +00:00
Evert Daniel Romero Garrido 63ba5553db Edited with Bitbucket 2026-04-16 21:51:56 +00:00
Evert Daniel Romero Garrido dd2f31ec2a fix(pipeline): corregir OIDC token handling y backend region validation
- Escribe BITBUCKET_STEP_OIDC_TOKEN a archivo temporal para evitar
  OSError: File name too long en el decoder JWT
- Python lee token via stdin en lugar de pasar JWT como filename
- Agrega skip_region_validation = true en backend.dev.hcl y backend.prod.hcl
  para compatibilidad con mx-central-1
2026-04-16 13:37:36 -06:00
Evert Daniel Romero Garrido ce22f776ff feat(dns): simplify PROD Route 53 by using prod-sacc.ccsoft.mx directly
Switch PROD DNS from cross-account Route 53 management to a delegated
subdomain in the PROD AWS account (523761210517).

Changes:
- prod.tfvars: domain_name changed to prod-sacc.ccsoft.mx
- provider.tf: removed aws.route53 cross-account provider
- main.tf: removed prod-specific Route 53 resources and data sources;
  cert_validation and main records now use default provider for all envs
- outputs.tf: removed indexed references to main_prod resource
2026-04-16 10:33:13 -06:00
Evert Daniel Romero Garrido cbae04ab3f fix(oidc): reemplaza placeholder por UUID real del repo proyectosacc 2026-04-15 12:51:48 -06:00
Evert Daniel Romero Garrido 744c5d1413 feat(iam): implementa autenticación OIDC entre Bitbucket Pipelines y AWS
- Agrega aws_iam_openid_connect_provider y roles IAM para DEV/PROD
- Actualiza bitbucket-pipelines.yml para usar OIDC en steps 03, 05, 07
- Crea script helper scripts/aws-oidc-setup.sh
- Agrega provider tls en terraform/provider.tf
- Documenta el flujo completo en docs/14-oidc-bitbucket-aws.md

Elimina la dependencia de AWS_ACCESS_KEY_ID y AWS_SECRET_ACCESS_KEY
estáticos en el pipeline, permitiendo autenticación sin credenciales
de larga vida via AssumeRoleWithWebIdentity.

Refs: cuenta DEV 668889063715, PROD 523761210517
2026-04-15 12:50:31 -06:00
Evert Daniel Romero Garrido bc3ff913cf chore(terraform): actualiza provider AWS a >=5.94.0 para soporte mx-central-1 y configura password RDS dev 2026-04-15 12:43:37 -06:00
Evert Daniel Romero Garrido cbea3e932b feat(ci): integra Terraform en pipeline de Bitbucket Pipelines
- Agrega paso 03_terraform para DEV y PROD con init, plan y apply
- Crea backend.dev.hcl para configuración explícita de estado DEV
- Refactoriza Route53/ACM en main.tf para soportar PROD cross-account
  usando count condicional sin romper estado de DEV
- Descomenta provider aws.route53 en provider.tf
- Añade domain_name faltante en prod.tfvars y confirma dev.tfvars
- Corrige output route53_record para recursos con count
- Elimina errored.tfstate corrupto local
- Incluye permiso sts:AssumeRole en IAM policy para Route53 cross-account
2026-04-14 19:40:57 -06:00
Evert Daniel Romero Garrido 3fe8cb1391 chore(ci): fix S3 artifacts bucket references in install step and secure terraform tfvars
- Use DEV_S3_ARTIFACTS_BUCKET and PROD_S3_ARTIFACTS_BUCKET in 06_install
  instead of generic S3_ARTIFACTS_BUCKET to prevent cross-env reads
- Add terraform/environments/*.tfvars to .gitignore to prevent secret leaks
- Update prod backend state bucket name to proyectosacc-specific bucket
- Add CI/CD credential policy documentation
2026-04-14 16:01:30 -06:00
Evert Daniel Romero Garrido 85297b12a2 Initial commit: Terraform infrastructure, pipelines, docs and scripts 2026-04-14 14:53:05 -06:00