AWSTemplateFormatVersion: '2010-09-09'
Description: 'Fixed: Custom VPC EC2 with Management Tools (AL2023)'

Parameters:
  KeyName:
    Description: 'Name of an existing EC2 KeyPair to enable SSH access'
    Type: 'AWS::EC2::KeyPair::KeyName'

  SgIngressSshCidr:
    Description: 'IP range allowed to SSH into the EC2 instance'
    Type: String
    Default: 0.0.0.0/0
    AllowedPattern: '(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/(\d{1,2})'
    ConstraintDescription: 'must be a valid IP CIDR range (x.x.x.x/x)'

  LatestAmiId:
    Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
    Default: '/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64'

Resources:
  # 1. VPC 및 네트워크 설정
  MyVPC:
    Type: 'AWS::EC2::VPC'
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: My-VPC

  MyInternetGateway:
    Type: 'AWS::EC2::InternetGateway'
    Properties: # 누락되었던 Properties 추가
      Tags:
        - Key: Name
          Value: My-IGW

  MyIGWAttachment:
    Type: 'AWS::EC2::VPCGatewayAttachment'
    Properties:
      VpcId: !Ref MyVPC
      InternetGatewayId: !Ref MyInternetGateway

  MyPublicSN:
    Type: 'AWS::EC2::Subnet'
    Properties:
      VpcId: !Ref MyVPC
      AvailabilityZone: !Select [ 0, !GetAZs '' ]
      CidrBlock: 10.0.0.0/24 # 두 번째 파일의 서브넷 대역 유지
      MapPublicIpOnLaunch: true
      Tags:
        - Key: Name
          Value: My-Public-SN

  MyPublicRT:
    Type: 'AWS::EC2::RouteTable'
    Properties:
      VpcId: !Ref MyVPC
      Tags:
        - Key: Name
          Value: My-Public-RT

  DefaultPublicRoute:
    Type: 'AWS::EC2::Route'
    DependsOn: MyIGWAttachment
    Properties:
      RouteTableId: !Ref MyPublicRT
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref MyInternetGateway

  MyPublicSNRouteTableAssociation:
    Type: 'AWS::EC2::SubnetRouteTableAssociation'
    Properties:
      SubnetId: !Ref MyPublicSN
      RouteTableId: !Ref MyPublicRT

  # 2. 보안 그룹
  ManagementSecurityGroup:
    Type: 'AWS::EC2::SecurityGroup'
    Properties:
      GroupDescription: 'Allow SSH and HTTP access'
      VpcId: !Ref MyVPC
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: !Ref SgIngressSshCidr
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0
      Tags:
        - Key: Name
          Value: KOPS-EC2-SG

  # 3. EC2 인스턴스 (NetworkInterfaces 설정을 통한 고정 IP 할당)
  ManagementEC2:
    Type: 'AWS::EC2::Instance'
    Properties:
      InstanceType: 't3.small'
      ImageId: !Ref LatestAmiId
      KeyName: !Ref KeyName
      NetworkInterfaces:
        - DeviceIndex: 0
          SubnetId: !Ref MyPublicSN
          GroupSet:
            - !Ref ManagementSecurityGroup
          AssociatePublicIpAddress: true
          PrivateIpAddress: 10.0.0.11 # 두 번째 파일의 요구사항 반영
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash
          # 기본 환경 설정
          hostnamectl --static set-hostname mgmt-server
          ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime
          dnf update -y
          dnf install -y tree jq git htop wget unzip tar

          # 툴 설치 (kubectl, kops, helm)
          cd /root
          curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
          install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
          
          curl -Lo kops https://github.com/kubernetes/kops/releases/download/$(curl -s https://api.github.com/repos/kubernetes/kops/releases/latest | grep tag_name | cut -d '"' -f 4)/kops-linux-amd64
          chmod +x kops
          mv kops /usr/local/bin/kops

          curl -s https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 | bash

          # AWS CLI v2
          curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
          unzip awscliv2.zip
          ./aws/install
          echo "export AWS_DEFAULT_REGION=${AWS::Region}" >> /etc/profile

          # Terraform
          dnf install -y yum-utils
          dnf config-manager --add-repo https://rpm.releases.hashicorp.com/AmazonLinux/hashicorp.repo
          dnf install -y terraform

          # Docker
          dnf install -y docker
          systemctl start docker
          systemctl enable docker
          usermod -aG docker ec2-user

          # 사용자 편의 설정 (Alias 등)
          echo 'alias k=kubectl' >> /etc/profile
          echo 'alias vi=vim' >> /etc/profile
          echo 'alias wa="watch -d kubectl get svc,no,pods,deploy,rs"' >> /etc/profile
          echo 'source <(kubectl completion bash)' >> /etc/profile
          echo "sudo su -" >> /home/ec2-user/.bashrc

          # kube-ps1 설치
          git clone https://github.com/jonmosco/kube-ps1.git /root/kube-ps1
          cat <<EOT >> /root/.bash_profile
          source /root/kube-ps1/kube-ps1.sh
          KUBE_PS1_SYMBOL_ENABLE=false
          PS1='\$(kube_ps1)'\$PS1
          EOT

          # Nginx 설치 (작동 확인용)
          dnf install -y nginx
          systemctl start nginx
          systemctl enable nginx
          echo "<h1>Management Server (10.0.0.11) Ready!</h1>" > /usr/share/nginx/html/index.html

      Tags:
        - Key: Name
          Value: seo-ec2-2026-02-26

Outputs:
  InstancePublicIp:
    Description: 'Public IP of the EC2 instance'
    Value: !GetAtt ManagementEC2.PublicIp
  VpcId:
    Description: 'VPC ID'
    Value: !Ref MyVPC