AWSTemplateFormatVersion: '2010-09-09'
Description: 'EC2 Instance with Nginx Auto-Install (Ubuntu 22.04 - Dynamic AMI)'

Parameters:
  KeyName:
    Description: 'Name of an existing EC2 KeyPair'
    Type: 'AWS::EC2::KeyPair::KeyName'
  # 최신 Ubuntu 22.04 AMI ID를 자동으로 가져오는 SSM 파라미터
  LatestAmiId:
    Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
    Default: '/aws/service/canonical/ubuntu/server/22.04/stable/current/amd64/hvm/ebs-gp2/ami-id'

Resources:
  WebServerSecurityGroup:
    Type: 'AWS::EC2::SecurityGroup'
    Properties:
      GroupDescription: 'Enable SSH and HTTP access'
      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

  MyEC2Instance:
    Type: 'AWS::EC2::Instance'
    Properties:
      ImageId: !Ref LatestAmiId # 위에서 정의한 SSM 파라미터 참조
      InstanceType: 't3.micro'
      KeyName: !Ref KeyName
      SecurityGroups:
        - !Ref WebServerSecurityGroup
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash
          apt-get update -y
          apt-get install -y nginx
          systemctl start nginx
          systemctl enable nginx
          echo "<h1>Hello from Ubuntu 22.04 & CloudFormation!</h1><p>Stack Name: ${AWS::StackName}</p>" > /var/www/html/index.html
      Tags:
        - Key: Name
          Value: Ubuntu-Nginx-Server

Outputs:
  WebsiteURL:
    Description: 'URL for the web server'
    Value: !Sub 'http://${MyEC2Instance.PublicIp}'