AWSTemplateFormatVersion: '2010-09-09'
Description: VPC B with Public Subnet and EC2 Instance

Parameters:
  # 1. 키 페어 입력 (필수)
  KeyName:
    Description: Name of an existing EC2 KeyPair to enable SSH access to the instance
    Type: AWS::EC2::KeyPair::KeyName
    ConstraintDescription: must be the name of an existing EC2 KeyPair.

  # 2. VPC 및 서브넷 설정
  VpcCidr:
    Type: String
    Default: 10.0.0.0/16
  PublicSubnetCidr:
    Type: String
    Default: 10.0.1.0/24
  
  # 3. 최신 Amazon Linux 2023 AMI ID 자동 조회 (SSM Parameter Store 사용)
  LatestAmiId:
    Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
    Default: '/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64'

Resources:
  # --- 네트워크 구성 (이전과 동일) ---
  VPCB:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: !Ref VpcCidr
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags: [{Key: Name, Value: VPC-B}]

  InternetGateway:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags: [{Key: Name, Value: VPC-B-IGW}]

  GatewayAttachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      VpcId: !Ref VPCB
      InternetGatewayId: !Ref InternetGateway

  PublicSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPCB
      CidrBlock: !Ref PublicSubnetCidr
      MapPublicIpOnLaunch: true # 공인 IP 자동 할당
      AvailabilityZone: !Select [ 0, !GetAZs '' ]
      Tags: [{Key: Name, Value: VPC-B-Public-Subnet}]

  PublicRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref VPCB
      Tags: [{Key: Name, Value: VPC-B-Public-RT}]

  PublicRoute:
    Type: AWS::EC2::Route
    DependsOn: GatewayAttachment
    Properties:
      RouteTableId: !Ref PublicRouteTable
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref InternetGateway

  PublicSubnetRouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PublicSubnet
      RouteTableId: !Ref PublicRouteTable

  # --- 서버 및 보안 구성 (새로 추가됨) ---
  
  # 4. 보안 그룹: SSH(22) 허용
  InstanceSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Enable SSH access via port 22
      VpcId: !Ref VPCB
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0 # 주의: 실무에서는 본인의 IP(예: 203.0.113.0/32)로 제한하는 것이 좋습니다.
      Tags: [{Key: Name, Value: VPC-B-SG}]

  # 5. EC2 인스턴스 생성
  PublicInstance:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: t3.micro
      ImageId: !Ref LatestAmiId
      KeyName: !Ref KeyName
      NetworkInterfaces: 
        - AssociatePublicIpAddress: true
          DeviceIndex: 0
          GroupSet: 
            - !Ref InstanceSecurityGroup
          SubnetId: !Ref PublicSubnet
      Tags: [{Key: Name, Value: VPC-B-Web-Server}]

Outputs:
  # 6. 접속 정보 출력
  InstancePublicIP:
    Description: Public IP address of the newly created EC2 instance
    Value: !GetAtt PublicInstance.PublicIp
  SSHCommand:
    Description: SSH connection command
    Value: !Sub "ssh -i ${KeyName}.pem ec2-user@${PublicInstance.PublicIp}"
