AWSTemplateFormatVersion: 2010-09-09
Description: >-
  AWS CloudFormation infrastructure Template
Parameters:
  VpcIdentifier:
    Type: String
    Description: The target VPC identifier.
  AmiIdentifier:
    Type: String
    Description: The AMI identifier to deploy.
  PublicSubnets:
    Type: CommaDelimitedList
    Description: The list of subnets where we would like to deploy the instances.
Resources:
  WebsiteEC2SecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Website EC2 security group 
      SecurityGroupEgress:
        - IpProtocol: -1
          CidrIp: 0.0.0.0/0
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0
      VpcId: !Ref VpcIdentifier
  WebsiteLaunchConfig:
    Type: AWS::AutoScaling::LaunchConfiguration
    Properties:
      AssociatePublicIpAddress: false
      ImageId: !Ref AmiIdentifier
      InstanceType: t2.micro
      SecurityGroups:
        - !Ref WebsiteEC2SecurityGroup
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash
          sudo systemctl start httpd
  WebsiteScalingGroup:
    Type: AWS::AutoScaling::AutoScalingGroup
    Properties:
      LaunchConfigurationName: !Ref WebsiteLaunchConfig
      AvailabilityZones:
        - Fn::Select:
          - 0
          - Fn::GetAZs: !Ref AWS::Region
        - Fn::Select:
          - 1
          - Fn::GetAZs: !Ref AWS::Region
      VPCZoneIdentifier: !Ref PublicSubnets
      DesiredCapacity: 1
      MaxSize: 1
      MinSize: 1
      TargetGroupARNs:
        - !Ref WebsiteTargetGroup
  WebsiteTargetGroup:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      Port: 80
      Protocol: HTTP
      VpcId: !Ref VpcIdentifier
  WebsiteLoadBalancer:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    Properties:
      Type: application
      Scheme: internet-facing
      SecurityGroups:
        - !Ref WebsiteLoadBalancerSecurityGroup
      Subnets: !Ref PublicSubnets
  WebsiteLoadBalancerSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Website EC2 security group 
      SecurityGroupEgress:
        - IpProtocol: -1
          CidrIp: 0.0.0.0/0
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0
      VpcId: !Ref VpcIdentifier
  WebsiteLoadBlancerListener:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties: 
      LoadBalancerArn: !Ref WebsiteLoadBalancer
      Port: 80
      Protocol: HTTP
      DefaultActions:
        - Type: forward
          TargetGroupArn: !Ref WebsiteTargetGroup
