AWSTemplateFormatVersion: '2010-09-09'
Description: 'EC2 Instance on Default VPC with Amazon Linux 2023'

Parameters:
  KeyName:
    Type: 'AWS::EC2::KeyPair::KeyName'
    Description: 'Name of an existing EC2 KeyPair'

  # 최신 Amazon Linux 2023 AMI를 자동으로 가져오는 파라미터
  LatestAmiId:
    Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
    Default: '/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64'

Resources:
  # 보안 그룹 (VpcId를 생략하면 기본 VPC에 자동 생성됨)
  WebServerSecurityGroup:
    Type: 'AWS::EC2::SecurityGroup'
    Properties:
      GroupDescription: 'Allow SSH and HTTP access in Default VPC'
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0

  # EC2 인스턴스
  MyEC2Instance:
    Type: 'AWS::EC2::Instance'
    Properties:
      ImageId: !Ref LatestAmiId
      InstanceType: 't3.micro'
      KeyName: !Ref KeyName
      # 보안 그룹 연결
      SecurityGroupIds: 
        - !Ref WebServerSecurityGroup
      # 웹 서버 자동 설치
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash
          dnf update -y
          dnf install -y nginx
          systemctl start nginx
          systemctl enable nginx
          echo "<h1>Welcome to Amazon Linux 2023 on Default VPC!</h1>" > /usr/share/nginx/html/index.html
      Tags:
        - Key: Name
          Value: DefaultVPC-AL2023-Server

Outputs:
  PublicIp:
    Description: 'Public IP of the EC2 instance'
    Value: !GetAtt MyEC2Instance.PublicIp
  WebsiteURL:
    Description: 'URL to access the Nginx web server'
    Value: !Sub 'http://\${MyEC2Instance.PublicIp}'
