AWSTemplateFormatVersion: "2010-09-09"
Description: >-
  cloud path, curso SAA-C03, labs 07a y 07b. Una VPC con dos subredes publicas
  (para el Application Load Balancer) y dos privadas sin salida a internet
  (para las instancias), un ALB, una launch template con IMDSv2 obligatorio y
  un grupo de Auto Scaling de 2 a 4 instancias con health check de ELB y una
  politica de target tracking sobre la CPU promedio. Gasta credito: el ALB cobra
  por hora y por LCU, y las instancias por hora. Borra la pila al terminar.

Parameters:
  TipoDeInstancia:
    Type: String
    Description: Tipos Free tier eligible para cuentas creadas desde el 15 de julio de 2025 (arquitectura x86).
    AllowedValues: [t3.micro, t3.small]
    Default: t3.micro
  ImagenAmazonLinux:
    Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
    Description: Parametro publico de AWS con la AMI mas reciente de Amazon Linux 2023.
    Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64
  CpuObjetivo:
    Type: Number
    Description: Objetivo de la politica de target tracking (CPU promedio del grupo, en porcentaje).
    MinValue: 10
    MaxValue: 90
    Default: 50

Resources:
  Vpc:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.71.0.0/16
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: cloudpath-saa-lab07
        - Key: cloudpath:lab
          Value: saa-lab07

  InternetGateway:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - Key: Name
          Value: cloudpath-saa-lab07-igw
        - Key: cloudpath:lab
          Value: saa-lab07

  ConexionGateway:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      VpcId: !Ref Vpc
      InternetGatewayId: !Ref InternetGateway

  SubredPublicaA:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref Vpc
      CidrBlock: 10.71.0.0/24
      AvailabilityZone: !Select [0, !GetAZs ""]
      Tags:
        - Key: Name
          Value: cloudpath-saa-lab07-publica-a
        - Key: cloudpath:lab
          Value: saa-lab07

  SubredPublicaB:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref Vpc
      CidrBlock: 10.71.1.0/24
      AvailabilityZone: !Select [1, !GetAZs ""]
      Tags:
        - Key: Name
          Value: cloudpath-saa-lab07-publica-b
        - Key: cloudpath:lab
          Value: saa-lab07

  # Subredes de aplicacion: sin ruta a internet. Las instancias no la necesitan:
  # el servidor web usa Python, que ya viene en Amazon Linux 2023.
  SubredAppA:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref Vpc
      CidrBlock: 10.71.10.0/24
      AvailabilityZone: !Select [0, !GetAZs ""]
      Tags:
        - Key: Name
          Value: cloudpath-saa-lab07-app-a
        - Key: cloudpath:lab
          Value: saa-lab07

  SubredAppB:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref Vpc
      CidrBlock: 10.71.11.0/24
      AvailabilityZone: !Select [1, !GetAZs ""]
      Tags:
        - Key: Name
          Value: cloudpath-saa-lab07-app-b
        - Key: cloudpath:lab
          Value: saa-lab07

  TablaPublica:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref Vpc
      Tags:
        - Key: Name
          Value: cloudpath-saa-lab07-publica
        - Key: cloudpath:lab
          Value: saa-lab07

  RutaAInternet:
    Type: AWS::EC2::Route
    DependsOn: ConexionGateway
    Properties:
      RouteTableId: !Ref TablaPublica
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref InternetGateway

  AsociacionPublicaA:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref SubredPublicaA
      RouteTableId: !Ref TablaPublica

  AsociacionPublicaB:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref SubredPublicaB
      RouteTableId: !Ref TablaPublica

  TablaApp:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref Vpc
      Tags:
        - Key: Name
          Value: cloudpath-saa-lab07-app
        - Key: cloudpath:lab
          Value: saa-lab07

  AsociacionAppA:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref SubredAppA
      RouteTableId: !Ref TablaApp

  AsociacionAppB:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref SubredAppB
      RouteTableId: !Ref TablaApp

  GrupoAlb:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Lab 07 de cloud path. ALB, acepta HTTP desde internet.
      VpcId: !Ref Vpc
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0
          Description: HTTP desde internet
      Tags:
        - Key: Name
          Value: cloudpath-saa-lab07-alb
        - Key: cloudpath:lab
          Value: saa-lab07

  GrupoWeb:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Lab 07 de cloud path. Instancias, solo aceptan HTTP del grupo del ALB.
      VpcId: !Ref Vpc
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          SourceSecurityGroupId: !Ref GrupoAlb
          Description: HTTP solo desde el ALB
      Tags:
        - Key: Name
          Value: cloudpath-saa-lab07-web
        - Key: cloudpath:lab
          Value: saa-lab07

  PlantillaDeLanzamiento:
    Type: AWS::EC2::LaunchTemplate
    Properties:
      LaunchTemplateName: !Sub "${AWS::StackName}-web"
      LaunchTemplateData:
        ImageId: !Ref ImagenAmazonLinux
        InstanceType: !Ref TipoDeInstancia
        SecurityGroupIds:
          - !Ref GrupoWeb
        MetadataOptions:
          HttpTokens: required
          HttpEndpoint: enabled
        # Metricas cada minuto: el grupo reacciona antes. Se cobra como metricas de CloudWatch.
        Monitoring:
          Enabled: true
        TagSpecifications:
          - ResourceType: instance
            Tags:
              - Key: Name
                Value: cloudpath-saa-lab07-web
              - Key: cloudpath:lab
                Value: saa-lab07
          - ResourceType: volume
            Tags:
              - Key: cloudpath:lab
                Value: saa-lab07
        UserData:
          Fn::Base64: |
            #!/bin/bash
            # Servidor web del lab 07 de cloud path. Sin paquetes extra: usa Python de Amazon Linux 2023.
            # GET /       instancia y zona que atendio la peticion
            # GET /salud  health check del target group
            # GET /carga  pone las 2 vCPU al 100 % por 120 s (lab 07b)
            mkdir -p /opt/cloudpath
            TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 300")
            ID=$(curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/instance-id)
            ZONA=$(curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/placement/availability-zone)
            cat > /opt/cloudpath/web.py <<EOF
            import subprocess
            from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
            ID, ZONA = "$ID", "$ZONA"
            activos = []
            class H(BaseHTTPRequestHandler):
                def responder(self, texto):
                    cuerpo = texto.encode()
                    self.send_response(200)
                    self.send_header("Content-Type", "text/html; charset=utf-8")
                    self.send_header("Content-Length", str(len(cuerpo)))
                    self.end_headers()
                    self.wfile.write(cuerpo)
                def do_GET(self):
                    global activos
                    if self.path == "/salud":
                        return self.responder("ok")
                    if self.path == "/carga":
                        activos = [p for p in activos if p.poll() is None]
                        while len(activos) < 2:
                            activos.append(subprocess.Popen(["timeout", "120", "sh", "-c", "while :; do :; done"]))
                        return self.responder(f"<p>{ID} ({ZONA}): CPU al 100 % por 120 s</p>")
                    self.responder(f"<h1>cloud path, lab 07</h1><p>Te atendio {ID} en la zona {ZONA}</p>")
                def log_message(self, *args):
                    pass
            ThreadingHTTPServer(("", 80), H).serve_forever()
            EOF
            cat > /etc/systemd/system/cloudpath-web.service <<EOF
            [Unit]
            Description=Servidor web del lab 07 de cloud path
            After=network-online.target
            [Service]
            ExecStart=/usr/bin/python3 /opt/cloudpath/web.py
            Restart=always
            [Install]
            WantedBy=multi-user.target
            EOF
            systemctl daemon-reload
            systemctl enable --now cloudpath-web

  GrupoDeDestinos:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      VpcId: !Ref Vpc
      Protocol: HTTP
      Port: 80
      TargetType: instance
      HealthCheckPath: /salud
      HealthCheckIntervalSeconds: 10
      HealthyThresholdCount: 2
      UnhealthyThresholdCount: 2
      TargetGroupAttributes:
        - Key: deregistration_delay.timeout_seconds
          Value: "30"
      Tags:
        - Key: cloudpath:lab
          Value: saa-lab07

  Balanceador:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    DependsOn: RutaAInternet
    Properties:
      Type: application
      Scheme: internet-facing
      Subnets:
        - !Ref SubredPublicaA
        - !Ref SubredPublicaB
      SecurityGroups:
        - !Ref GrupoAlb
      Tags:
        - Key: Name
          Value: cloudpath-saa-lab07
        - Key: cloudpath:lab
          Value: saa-lab07

  ListenerHttp:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      LoadBalancerArn: !Ref Balanceador
      Protocol: HTTP
      Port: 80
      DefaultActions:
        - Type: forward
          TargetGroupArn: !Ref GrupoDeDestinos

  GrupoAutoScaling:
    Type: AWS::AutoScaling::AutoScalingGroup
    DependsOn: ListenerHttp
    Properties:
      MinSize: "2"
      MaxSize: "4"
      DesiredCapacity: "2"
      VPCZoneIdentifier:
        - !Ref SubredAppA
        - !Ref SubredAppB
      LaunchTemplate:
        LaunchTemplateId: !Ref PlantillaDeLanzamiento
        Version: !GetAtt PlantillaDeLanzamiento.LatestVersionNumber
      TargetGroupARNs:
        - !Ref GrupoDeDestinos
      HealthCheckType: ELB
      HealthCheckGracePeriod: 120
      DefaultInstanceWarmup: 60
      Tags:
        - Key: cloudpath:lab
          Value: saa-lab07
          PropagateAtLaunch: false

  PoliticaCpu:
    Type: AWS::AutoScaling::ScalingPolicy
    Properties:
      AutoScalingGroupName: !Ref GrupoAutoScaling
      PolicyType: TargetTrackingScaling
      TargetTrackingConfiguration:
        PredefinedMetricSpecification:
          PredefinedMetricType: ASGAverageCPUUtilization
        TargetValue: !Ref CpuObjetivo

Outputs:
  UrlDelBalanceador:
    Description: Abre esta direccion en el navegador y recarga varias veces (las instancias tardan un par de minutos).
    Value: !Sub "http://${Balanceador.DNSName}"
  NombreDelGrupo:
    Description: Grupo de Auto Scaling para ver su actividad en la consola de EC2.
    Value: !Ref GrupoAutoScaling
