AWSTemplateFormatVersion: '2010-09-09'
Description: >-
  A simple web application behind an Application Load Balancer, running on an
  Auto Scaling Group of Amazon Linux 2023 instances in the private subnets.
  Replacing the AmazonMachineImage parameter triggers a blue/green rollout,
  which is how the patching automation deploys a freshly built AMI.

Parameters:
  BaselineVpcStack:
    Type: String
    Description: Name of the base network stack to import the VPC and subnets from.

  NumberOfInstanceCluster:
    Type: String
    Default: "2"
    Description: Desired number of instances in the Auto Scaling Group.

  MaxNumberOfInstanceCluster:
    Type: String
    Default: "2"
    Description: Maximum number of instances in the Auto Scaling Group.

  InstanceType:
    Type: String
    Default: t3.small
    AllowedValues:
      - t3.micro
      - t3.small
      - t3.medium
    Description: Instance size for the web servers.

  LatestAmiId:
    Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
    Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64
    Description: >-
      Public SSM parameter that resolves to the newest Amazon Linux 2023 AMI.
      Used only when AmazonMachineImage is left empty.

  AmazonMachineImage:
    Type: String
    Default: ""
    Description: >-
      A specific AMI ID. Leave empty on first deployment. The Systems Manager
      automation sets this to the AMI it just built.

Conditions:
  # Fall back to the latest Amazon Linux 2023 AMI until an explicit ID is given.
  UseLatestAmi: !Equals [ !Ref AmazonMachineImage, "" ]

Resources:
#----------------------------------------------------------------------------------------
# Public entry point: internet-facing load balancer on port 80
#----------------------------------------------------------------------------------------
  Pattern3ALB:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    Properties:
      Type: application
      Scheme: internet-facing
      IpAddressType: ipv4
      SecurityGroups:
        - !Ref Pattern3ELBSecurityGroup
      Subnets:
        - Fn::ImportValue: !Sub "${BaselineVpcStack}-PublicSubnet1"
        - Fn::ImportValue: !Sub "${BaselineVpcStack}-PublicSubnet2"
      Tags:
        - Key: Name
          Value: !Sub "${AWS::StackName}-ExternalALB"
        - Key: ResourceType
          Value: awsstudygroup-000099-imagebuilder

  Pattern3ALBTargetGroup:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      TargetType: instance
      HealthCheckEnabled: true
      HealthCheckIntervalSeconds: 30
      HealthCheckPath: /
      HealthCheckPort: traffic-port
      HealthCheckProtocol: HTTP
      HealthCheckTimeoutSeconds: 5
      HealthyThresholdCount: 3
      UnhealthyThresholdCount: 5
      Matcher:
        HttpCode: '200'
      TargetGroupAttributes:
        - Key: deregistration_delay.timeout_seconds
          Value: 60
      VpcId:
        Fn::ImportValue: !Sub "${BaselineVpcStack}-VpcId"
      Port: 80
      Protocol: HTTP
      Tags:
        - Key: Name
          Value: !Sub "${AWS::StackName}-ExternalALBTargetGroup"
        - Key: ResourceType
          Value: awsstudygroup-000099-imagebuilder

  Pattern3ALBListener:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      LoadBalancerArn: !Ref Pattern3ALB
      Port: 80
      Protocol: HTTP
      DefaultActions:
        - Type: forward
          TargetGroupArn: !Ref Pattern3ALBTargetGroup

#----------------------------------------------------------------------------------------
# Security Groups
#----------------------------------------------------------------------------------------
  Pattern3ELBSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Allows HTTP from the internet to the load balancer
      VpcId:
        Fn::ImportValue: !Sub "${BaselineVpcStack}-VpcId"
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: '0.0.0.0/0'
          Description: HTTP from the internet. The workshop skips HTTPS to stay simple.
      Tags:
        - Key: Name
          Value: !Sub "${AWS::StackName}-ExternalELBSecurityGroup"
        - Key: ResourceType
          Value: awsstudygroup-000099-imagebuilder

  Pattern3InstanceSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Allows HTTP only from the load balancer
      VpcId:
        Fn::ImportValue: !Sub "${BaselineVpcStack}-VpcId"
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          SourceSecurityGroupId: !Ref Pattern3ELBSecurityGroup
          Description: HTTP from the load balancer security group
      Tags:
        - Key: Name
          Value: !Sub "${AWS::StackName}-InstanceSecurityGroup"
        - Key: ResourceType
          Value: awsstudygroup-000099-imagebuilder

#----------------------------------------------------------------------------------------
# Launch Template. Changing the AMI creates a new version, which is what
# makes the Auto Scaling Group roll out replacement instances.
#----------------------------------------------------------------------------------------
  Pattern3LaunchTemplate:
    Type: AWS::EC2::LaunchTemplate
    Properties:
      LaunchTemplateName: !Sub "${AWS::StackName}-launch-template"
      LaunchTemplateData:
        ImageId: !If [ UseLatestAmi, !Ref LatestAmiId, !Ref AmazonMachineImage ]
        InstanceType: !Ref InstanceType
        IamInstanceProfile:
          Name: !Ref Pattern3Ec2InstanceProfile
        SecurityGroupIds:
          - !Ref Pattern3InstanceSecurityGroup
        MetadataOptions:
          HttpEndpoint: enabled
          HttpTokens: required
          HttpPutResponseHopLimit: 1
        Monitoring:
          Enabled: true
        BlockDeviceMappings:
          - DeviceName: /dev/xvda
            Ebs:
              VolumeSize: 8
              VolumeType: gp3
              Encrypted: true
              DeleteOnTermination: true
        TagSpecifications:
          - ResourceType: instance
            Tags:
              - Key: Name
                Value: !Sub "${AWS::StackName}-AutoScalingGroupInstance"
              - Key: ResourceType
                Value: awsstudygroup-000099-imagebuilder
          - ResourceType: volume
            Tags:
              - Key: ResourceType
                Value: awsstudygroup-000099-imagebuilder
        UserData:
          Fn::Base64: !Sub |
            #!/bin/bash -x
            # Deliberately not using 'set -e'. If cfn-init fails and the shell
            # exits early, cfn-signal never runs and the stack waits for the full
            # timeout before reporting "Received 0 SUCCESS signal(s)". Always
            # signal so failures surface immediately with a real reason.

            # Amazon Linux 2023 does not ship aws-cfn-bootstrap preinstalled.
            # Retry a few times in case of a transient network problem.
            for i in 1 2 3; do
              dnf install -y aws-cfn-bootstrap && break
              echo "Attempt $i to install aws-cfn-bootstrap failed, retrying in 15s..."
              sleep 15
            done

            if [ ! -x /opt/aws/bin/cfn-init ]; then
              echo "FATAL: could not install aws-cfn-bootstrap."
              echo "Usual cause: the private subnet has no route to the internet via NAT Gateway."
              exit 1
            fi

            /opt/aws/bin/cfn-init -v \
              --stack ${AWS::StackId} \
              --resource Pattern3LaunchTemplate \
              --configsets provision \
              --region ${AWS::Region}
            CFN_INIT_STATUS=$?

            /opt/aws/bin/cfn-signal -e $CFN_INIT_STATUS \
              --stack ${AWS::StackId} \
              --resource Pattern3ASG \
              --region ${AWS::Region}

            exit $CFN_INIT_STATUS
    Metadata:
      AWS::CloudFormation::Init:
        configSets:
          provision:
            - "webserver"
            - "application"
        webserver:
          # Amazon Linux 2023 has no package literally named 'php', 'php-fpm' or
          # 'php-cli'. Those are virtual provides offered by five different
          # packages (php8.1 through php8.5), so the version must be explicit.
          packages:
            yum:
              "httpd": []
              "php8.3": []
              "php8.3-cli": []
              "php8.3-fpm": []
          commands:
            01_enable_php_fpm:
              command: "systemctl enable --now php-fpm || systemctl enable --now php8.3-fpm"
            02_enable_httpd:
              command: "systemctl enable --now httpd"
        application:
          files:
            /var/www/html/index.html:
              content: |
                <!DOCTYPE html>
                <html lang="vi">
                  <head>
                    <meta charset="utf-8">
                    <title>FCAJ - AWS Study Group - Workshop 000099</title>
                  </head>
                  <body>
                    <h1>Welcome to FCAJ - AWS Study Group - Autonomous Patching Workshop</h1>
                  </body>
                </html>
              mode: "000644"
              owner: "root"
              group: "root"
            /var/www/html/details.php:
              content: |
                <?php
                  // IMDSv2 requires fetching a token before reading metadata.
                  $token = trim(shell_exec('curl -s -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 60"'));
                  $hdr   = '-H "X-aws-ec2-metadata-token: ' . $token . '"';

                  $ami        = trim(shell_exec('curl -s ' . $hdr . ' http://169.254.169.254/latest/meta-data/ami-id'));
                  $instanceId = trim(shell_exec('curl -s ' . $hdr . ' http://169.254.169.254/latest/meta-data/instance-id'));
                  $az         = trim(shell_exec('curl -s ' . $hdr . ' http://169.254.169.254/latest/meta-data/placement/availability-zone'));
                  $osRelease  = trim(shell_exec('cat /etc/system-release'));
                  $installed  = shell_exec("rpm -qa --queryformat '%{NAME} %{VERSION}-%{RELEASE}\n' | sort");

                  $packages = array_values(array_filter(array_map('trim', explode("\n", $installed))));

                  print "<h2>FCAJ - AWS Study Group - Workshop 000099</h2>";
                  print "<b>Operating System: </b>" . htmlspecialchars($osRelease) . "<br>";
                  print "<b>Amazon Image Id: </b>" . htmlspecialchars($ami) . "<br>";
                  print "<b>Instance Id: </b>" . htmlspecialchars($instanceId) . "<br>";
                  print "<b>Availability Zone: </b>" . htmlspecialchars($az) . "<br>";
                  print "<hr>";
                  print "<b>Installed Packages (" . count($packages) . "):</b><br>";
                  foreach ($packages as $line) {
                      print "<br>[" . htmlspecialchars($line) . "]";
                  }
                ?>
              mode: "000644"
              owner: "root"
              group: "root"
          commands:
            01_restart_web_stack:
              command: "systemctl restart php-fpm httpd || systemctl restart php8.3-fpm httpd"

#----------------------------------------------------------------------------------------
# Auto Scaling Group. AutoScalingReplacingUpdate builds a whole new group on the
# new AMI, waits for it to pass health checks, then swaps traffic over. That is
# the blue/green behaviour the patching automation relies on.
#----------------------------------------------------------------------------------------
  Pattern3ASG:
    Type: AWS::AutoScaling::AutoScalingGroup
    DependsOn: Pattern3ALBListener
    Properties:
      TargetGroupARNs:
        - !Ref Pattern3ALBTargetGroup
      MinSize: '0'
      MaxSize: !Ref MaxNumberOfInstanceCluster
      DesiredCapacity: !Ref NumberOfInstanceCluster
      LaunchTemplate:
        LaunchTemplateId: !Ref Pattern3LaunchTemplate
        Version: !GetAtt Pattern3LaunchTemplate.LatestVersionNumber
      HealthCheckType: ELB
      HealthCheckGracePeriod: 300
      VPCZoneIdentifier:
        - Fn::ImportValue: !Sub "${BaselineVpcStack}-PrivateSubnet1"
        - Fn::ImportValue: !Sub "${BaselineVpcStack}-PrivateSubnet2"
      Tags:
        - Key: Name
          PropagateAtLaunch: true
          Value: !Sub "${AWS::StackName}-AutoScalingGroupInstance"
        - Key: ResourceType
          PropagateAtLaunch: true
          Value: awsstudygroup-000099-imagebuilder
    UpdatePolicy:
      AutoScalingReplacingUpdate:
        WillReplace: true
    CreationPolicy:
      ResourceSignal:
        Count: !Ref NumberOfInstanceCluster
        Timeout: PT15M

#----------------------------------------------------------------------------------------
# Instance role. Only grants Systems Manager access, which is enough for
# Session Manager and leaves no need for SSH keys or a bastion host.
#----------------------------------------------------------------------------------------
  Pattern3Ec2InstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Path: /
      Roles: [ !Ref Pattern3Ec2InstanceRole ]

  Pattern3Ec2InstanceRole:
    Type: AWS::IAM::Role
    Properties:
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: [ ec2.amazonaws.com ]
            Action:
              - sts:AssumeRole
      Path: /
      Tags:
        - Key: ResourceType
          Value: awsstudygroup-000099-imagebuilder

Outputs:
  OutputPattern3ALBDNSName:
    Description: Open this in a browser to reach the application
    Value: !GetAtt Pattern3ALB.DNSName
  OutputPattern3ActiveAmiId:
    Description: AMI currently used by the Auto Scaling Group
    Value: !If [ UseLatestAmi, !Ref LatestAmiId, !Ref AmazonMachineImage ]
  OutputPattern3ALB:
    Description: Application Load Balancer
    Value: !Ref Pattern3ALB
    Export:
      Name: !Sub "${AWS::StackName}-ALB"
  OutputPattern3LaunchTemplate:
    Description: Launch Template ID
    Value: !Ref Pattern3LaunchTemplate
    Export:
      Name: !Sub "${AWS::StackName}-LaunchTemplate"
  OutputPattern3AutoScalingGroup:
    Description: Auto Scaling Group name
    Value: !Ref Pattern3ASG
    Export:
      Name: !Sub "${AWS::StackName}-AutoScalingGroup"
  OutputPattern3ELBSecurityGroup:
    Description: Load balancer security group
    Value: !Ref Pattern3ELBSecurityGroup
    Export:
      Name: !Sub "${AWS::StackName}-ELBSecurityGroup"
  OutputPattern3InstanceSecurityGroup:
    Description: Instance security group
    Value: !Ref Pattern3InstanceSecurityGroup
    Export:
      Name: !Sub "${AWS::StackName}-InstanceSecurityGroup"
