AWSTemplateFormatVersion: '2010-09-09'
Description: VPC B with Public/Private Subnets and IGW

Parameters:
  VpcCidr:
    Type: String
    Default: 10.0.0.0/16
  PublicSubnetCidr:
    Type: String
    Default: 10.0.1.0/24
  PrivateSubnetCidr:
    Type: String
    Default: 10.0.2.0/24

Resources:
  # 1. VPC 생성
  VPCB:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: !Ref VpcCidr
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: VPC-B

  # 2. 인터넷 게이트웨이 (IGW) 생성 및 연결
  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

  # 3. 서브넷 생성
  PublicSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPCB
      CidrBlock: !Ref PublicSubnetCidr
      MapPublicIpOnLaunch: true # EC2 생성 시 자동으로 공인 IP 할당
      AvailabilityZone: !Select [ 0, !GetAZs '' ] # 첫 번째 AZ 사용 (예: ap-northeast-2a)
      Tags:
        - Key: Name
          Value: VPC-B-Public-Subnet

  PrivateSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPCB
      CidrBlock: !Ref PrivateSubnetCidr
      AvailabilityZone: !Select [ 0, !GetAZs '' ]
      Tags:
        - Key: Name
          Value: VPC-B-Private-Subnet

  # 4. 라우팅 테이블 (표지판) 설정
  # Public Route Table: 모든 트래픽(0.0.0.0/0)을 IGW로 보냄
  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

  # 서브넷과 라우팅 테이블 연결 (Association)
  PublicSubnetRouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PublicSubnet
      RouteTableId: !Ref PublicRouteTable

  # Private Subnet은 별도 라우팅이 없으면 기본적으로 Local 통신만 가능 (안전함)
  PrivateRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref VPCB
      Tags:
        - Key: Name
          Value: VPC-B-Private-RT

  PrivateSubnetRouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PrivateSubnet
      RouteTableId: !Ref PrivateRouteTable

Outputs:
  VpcId:
    Value: !Ref VPCB
  PublicSubnetId:
    Value: !Ref PublicSubnet
  PrivateSubnetId:
    Value: !Ref PrivateSubnet
