본문 바로가기

IT 엔지니어/CLOUD

AWS - CloudFormation

 

[Cloud-Formation]

AWS에서 제공하는 IAC(Infrastructure as Code)
리소스 생성 및 설정 내용 
YAML JSON 형식으로 제작 및 관리 기능 제공 자동화 도구
 
 **인프라를 코드(IaC: Infrastructure as Code)**로 
 관리할 수 있게 해주는 AWS의 자동화 도구입니다.

쉽게 말하면...
“GUI로 하나하나 EC2, VPC, 보안그룹 만들지 말고, 
YAML 또는 JSON 템플릿 파일로 한 번에 자동 생성하자!”

[Cloud Fomration 순서]

  1. Parameter 코드 생성
    1. 사용자가 입력 및 선택할 설정 항목 정의
    2. [parameter] Parameters: KeyName: Description: EC2 KeyPair Type: AWS::EC2::KeyPair::KeyName ConstraintDescription: EC2 KeyPair LatestAmiId: Description: EC2 AMI Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>' Default: '/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2' AllowedValues: - /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2
  2. Resource 코드 생성
    1. Resource 하위 요소 정의 후 생성
    Resources:
      MyVPC01:
        Type: AWS::EC2::VPC
        Properties: 
          CidrBlock: 10.0.0.0/16
          EnableDnsSupport: true
          EnableDnsHostnames: true
          Tags:
            - Key: Name
              Value: MyVPC01
    
      MyIGW:
        Type: AWS::EC2::InternetGateway
        Properties: 
          Tags:
            - Key: Name
              Value: MyIGW
    
      MyIGWattachment:
        Type: AWS::EC2::VPCGatewayAttachment
        Properties:
          InternetGatewayId: !Ref MyIGW
          VpcId: !Ref MyVPC01
    
      MyPublicSubnet:
        Type: AWS::EC2::Subnet
        Properties:
          VpcId: !Ref MyVPC01
          AvailabilityZone: !Select [ 0, !GetAZs '' ]
          CidrBlock: 10.0.1.0/24
          MapPublicIpOnLaunch: true
          Tags:
            - Key: Name
              Value: MyPublicSubnet
    
      MyPublicRouting:
        Type: AWS::EC2::RouteTable
        Properties:
          VpcId: !Ref MyVPC01
          Tags:
            - Key: Name
              Value: MyPublicRouting
    
      MyPublicSubnetRoutingAssociation:
        Type: AWS::EC2::SubnetRouteTableAssociation
        Properties: 
          RouteTableId: !Ref MyPublicRouting
          SubnetId: !Ref MyPublicSubnet
    
      MyPublicDefault:
        Type: AWS::EC2::Route
        DependsOn: MyIGWattachment
        Properties:
          RouteTableId: !Ref MyPublicRouting
          DestinationCidrBlock: 0.0.0.0/0
          GatewayId: !Ref MyIGW
    
      MyPublicSecugroup:
        Type: AWS::EC2::SecurityGroup
        Properties:
          GroupDescription: Permit HTTP(80), HTTPS(443), SSH(22)
          VpcId: !Ref MyVPC01
          GroupName: MyPublicSecgroup
          Tags:
            - Key: Name
              Value: MyPublicSecgroup
          SecurityGroupIngress:
            - IpProtocol: tcp
              FromPort: 80
              ToPort: 80
              CidrIp: 0.0.0.0/0
            - IpProtocol: tcp
              FromPort: 443
              ToPort: 443
              CidrIp: 0.0.0.0/0
            - IpProtocol: tcp
              FromPort: 22
              ToPort: 22
              CidrIp: 0.0.0.0/0
    	
    	MyWeb:
    	Type: AWS::EC2::Instance
    	DependsOn: MyIGWattachment
    	Properties:
    		InstanceType: t3.micro
    		ImageId: !Ref LatestAmiId
    		KeyName: !Ref KeyName
    		Tags:
    		- Key: Name
    			Value: MyWeb
    		NetworkInterfaces: 
    			- DeviceIndex: 0
    				SubnetId: !Ref MyPublicSubnet
    				GroupSet:
    					- !Ref MyPublicSecgroup
    				AssociatePublicIpAddress: true
    				PrivateIpAddress: 10.0.1.101
    		UserData:
    			Fn::Base64:
    				!Sub | 
    					#!/bin/bash
    					export INSTANCE_ID=$(curl -s <http://169.254.169.254/latest/meta-data/instance-id>)
    					echo "root:aws1234!" | chpasswd
    					sed -i 's/^PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config
    					sed -i 's/^#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
    					sed -i 's/^#PermitRootLogin no/PermitRootLogin yes/' /etc/ssh/sshd_config
    					systemctl restart sshd
    					dnf -y install httpd
    					echo "<h1>${INSTANCE_ID} (AUTO SCALING) Welcome to AWS WEB Server</h1>" > /var/www/html/index.html
    					systemctl enable httpd
    					systemctl start httpd
    				
    
  3. YML 파일 생성
  4. Cloud Formation 스택 생성
    1. TAB이 아닌 SPACE
    Parameters:
      TokenV1:
        Description: "Token version 1"
        Type: String
        Default: "v1"
      TokenV2:
        Description: "Token version 2"
        Type: String
        Default: "v2" 
      KeyName:
        Description: EC2 KeyPair
        Type: AWS::EC2::KeyPair::KeyName
        ConstraintDescription: EC2 KeyPair
      LatestAmiId:
        Description: EC2 AMI
        Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
        Default: '/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64'
        AllowedValues:
          - /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64
    
    Resources:
      MyVPC01:
        Type: AWS::EC2::VPC
        Properties: 
          CidrBlock: 10.0.0.0/16
          EnableDnsSupport: true
          EnableDnsHostnames: true
          Tags:
            - Key: Name
              Value: MyVPC01
    
      MyIGW:
        Type: AWS::EC2::InternetGateway
        Properties: 
          Tags:
            - Key: Name
              Value: MyIGW
    
      MyIGWattachment:
        Type: AWS::EC2::VPCGatewayAttachment
        Properties:
          InternetGatewayId: !Ref MyIGW
          VpcId: !Ref MyVPC01
    
      MyPublicSubnet:
        Type: AWS::EC2::Subnet
        Properties:
          VpcId: !Ref MyVPC01
          AvailabilityZone: !Select [ 0, !GetAZs '' ]
          CidrBlock: 10.0.1.0/24
          MapPublicIpOnLaunch: true
          Tags:
            - Key: Name
              Value: MyPublicSubnet
    
      MyPublicRouting:
        Type: AWS::EC2::RouteTable
        Properties:
          VpcId: !Ref MyVPC01
          Tags:
            - Key: Name
              Value: MyPublicRouting
    
      MyPublicSubnetRoutingAssociation:
        Type: AWS::EC2::SubnetRouteTableAssociation
        Properties: 
          RouteTableId: !Ref MyPublicRouting
          SubnetId: !Ref MyPublicSubnet
    
      MyPublicDefault:
        Type: AWS::EC2::Route
        DependsOn: MyIGWattachment
        Properties:
          RouteTableId: !Ref MyPublicRouting
          DestinationCidrBlock: 0.0.0.0/0
          GatewayId: !Ref MyIGW
    
      MyPublicSecugroup:
        Type: AWS::EC2::SecurityGroup
        Properties:
          GroupDescription: Permit HTTP(80), HTTPS(443), SSH(22)
          VpcId: !Ref MyVPC01
          GroupName: MyPublicSecgroup
          Tags:
            - Key: Name
              Value: MyPublicSecgroup
          SecurityGroupIngress:
            - IpProtocol: tcp
              FromPort: 80
              ToPort: 80
              CidrIp: 0.0.0.0/0
            - IpProtocol: tcp
              FromPort: 443
              ToPort: 443
              CidrIp: 0.0.0.0/0
            - IpProtocol: tcp
              FromPort: 22
              ToPort: 22
              CidrIp: 0.0.0.0/0
    
      MyWeb:
        Type: AWS::EC2::Instance
        DependsOn: MyIGWattachment
        Properties:
          InstanceType: t3.micro
          ImageId: !Ref LatestAmiId
          KeyName: !Ref KeyName
          Tags:
            - Key: Name
              Value: MyWeb
          NetworkInterfaces: 
            - DeviceIndex: 0
              SubnetId: !Ref MyPublicSubnet
              GroupSet:
                - !Ref MyPublicSecgroup
              AssociatePublicIpAddress: true
              PrivateIpAddress: 10.0.1.101
          UserData:
            Fn::Base64:
              !Sub |
                #!/bin/bash
                echo "root:aws1234!" | chpasswd
                sed -i 's/^PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config
                sed -i 's/^#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
                sed -i 's/^#PermitRootLogin no/PermitRootLogin yes/' /etc/ssh/sshd_config
                systemctl restart sshd
                dnf -y install httpd
                echo "<h1>$Welcome to AWS WEB Server</h1>" > /var/www/html/index.html
                systemctl enable httpd
                systemctl start httpd
    
    
  5. 리소스 생성 확인
{!NSTANCE_ID} = 문자열로 인식 / 리눅스 인스턴스 안에서만 변수로 인식
리눅스 이미지에 맞는 명령어 확인 필요
Depends on: 순서 중요
TAP 제외 SPACE로 공백 필요

Parameters:
  TokenV1:
    Description: "Token version 1"
    Type: String
    Default: "v1"
  TokenV2:
    Description: "Token version 2"
    Type: String
    Default: "v2" 
  KeyName:
    Description: EC2 KeyPair
    Type: AWS::EC2::KeyPair::KeyName
    ConstraintDescription: EC2 KeyPair
  LatestAmiId:
    Description: EC2 AMI
    Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
    Default: '/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64'
    AllowedValues:
      - /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64

Resources:
  # VPC 생성
  MyVPC01:
    Type: AWS::EC2::VPC
    Properties: 
      CidrBlock: 10.0.0.0/16
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: MyVPC01

  # EIP (Elastic IP) 할당
  MyEIP:
    Type: AWS::EC2::EIP
    Properties:
      Domain: vpc
      Tags:
        - Key: Name
          Value: MyEIP

# 퍼블릭 서브넷 1 생성
  MyPublicSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref MyVPC01
      AvailabilityZone: !Select [ 0, !GetAZs '' ]
      CidrBlock: 10.0.1.0/24
      MapPublicIpOnLaunch: true
      Tags:
        - Key: Name
          Value: MyPublicSubnet1

  # NAT Gateway 생성 (퍼블릭 서브넷에 배치)
  MyNAT:
    Type: AWS::EC2::NATGateway
    DependsOn: MyIGWattachment
    Properties:
      AllocationId: !GetAtt MyEIP.AllocationId
      SubnetId: !Ref MyPublicSubnet1
      Tags:
        - Key: Name
          Value: MyNAT
          
  # 인터넷 게이트웨이 생성
  MyIGW:
    Type: AWS::EC2::InternetGateway
    Properties: 
      Tags:
        - Key: Name
          Value: MyIGW

  # VPC에 인터넷 게이트웨이 연결
  MyIGWattachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      InternetGatewayId: !Ref MyIGW
      VpcId: !Ref MyVPC01

  
  # 퍼블릭 라우팅 테이블 생성
  MyPublicRouting:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref MyVPC01
      Tags:
        - Key: Name
          Value: MyPublicRouting

  # 퍼블릭 서브넷 라우팅 테이블과 연결
  MyPublicSubnetRoutingAssociation1:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties: 
      RouteTableId: !Ref MyPublicRouting
      SubnetId: !Ref MyPublicSubnet1

  # 퍼블릭 기본 라우트 설정
  MyPublicDefault:
    Type: AWS::EC2::Route
    DependsOn: MyIGWattachment
    Properties:
      RouteTableId: !Ref MyPublicRouting
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref MyIGW

  # 퍼블릭 보안 그룹 설정
  MyPublicSecugroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Permit HTTP(80), HTTPS(443), SSH(22)
      VpcId: !Ref MyVPC01
      GroupName: MyPublicSecgroup
      Tags:
        - Key: Name
          Value: MyPublicSecgroup
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0

  # 프라이빗 서브넷 생성
  MyPrivateSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref MyVPC01
      AvailabilityZone: !Select [ 0, !GetAZs '' ]
      CidrBlock: 10.0.100.0/24
      MapPublicIpOnLaunch: false  # 프라이빗 서브넷에서는 퍼블릭 IP를 할당하지 않음
      Tags:
        - Key: Name
          Value: MyPrivateSubnet1
          

  # NAT Gateway를 통한 라우팅을 위한 프라이빗 라우팅 테이블 생성
  MyPrivateRouting:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref MyVPC01
      Tags:
        - Key: Name
          Value: MyPrivateRouting

  # 프라이빗 서브넷 1과 라우팅 테이블 연결
  MyPrivateSubnetRoutingAssociation1:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties: 
      RouteTableId: !Ref MyPrivateRouting
      SubnetId: !Ref MyPrivateSubnet1

  # 프라이빗 기본 라우트 설정 (NAT Gateway 사용)
  MyPrivateDefault:
    Type: AWS::EC2::Route
    DependsOn: MyNAT
    Properties:
      RouteTableId: !Ref MyPrivateRouting
      DestinationCidrBlock: 0.0.0.0/0
      NatGatewayId: !Ref MyNAT

  # 프라이빗 보안 그룹 설정
  MyPrivateSecugroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Permit HTTP(80), HTTPS(443), SSH(22)
      VpcId: !Ref MyVPC01
      GroupName: MyPrivateSecgroup
      Tags:
        - Key: Name
          Value: MyPrivateSecgroup
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0
        - IpProtocol: "icmp"
          CidrIp: 0.0.0.0/0  # 모든 IP에서 ICMP를 허용 (보안을 고려해 제한할 수 있음)
          FromPort: "-1"  # ICMP 타입을 지정하지 않고 모든 타입 허용
          ToPort: "-1"    # ICMP 코드 역시 모든 코드 허용

  # 웹 서버 EC2 인스턴스 1 (프라이빗 서브넷에 배치)
  MyWeb1:
    Type: AWS::EC2::Instance
    DependsOn: MyNAT
    Properties:
      InstanceType: t3.micro
      ImageId: !Ref LatestAmiId
      KeyName: !Ref KeyName
      Tags:
        - Key: Name
          Value: MyWeb1
      NetworkInterfaces: 
        - DeviceIndex: 0
          SubnetId: !Ref MyPrivateSubnet1
          GroupSet:
            - !Ref MyPrivateSecugroup
          AssociatePrivateIpAddress: true
          PrivateIpAddress: 10.0.100.100
      UserData:
        Fn::Base64:
          !Sub |
            #!/bin/bash
            export INSTANCE_ID=$(curl -s <http://169.254.169.254/latest/meta-data/instance-id>)
            echo "root:aws1234!" | chpasswd
            sed -i 's/^PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config
            sed -i 's/^#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
            systemctl restart sshd
            dnf -y install httpd
            echo "<h1>${!INSTANCE_ID} (AUTO SCALING) Welcome to AWS WEB Server</h1>" > /var/www/html/index.html
            systemctl enable httpd
            systemctl start httpd

 
Parameters:
  TokenV1:
    Description: "Token version 1"
    Type: String
    Default: "v1"
  TokenV2:
    Description: "Token version 2"
    Type: String
    Default: "v2" 
  KeyName:
    Description: EC2 KeyPair
    Type: AWS::EC2::KeyPair::KeyName
    ConstraintDescription: EC2 KeyPair
  LatestAmiId:
    Description: EC2 AMI
    Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
    Default: '/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64'
    AllowedValues:
      - /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64

Resources:
  # VPC 생성
  MyVPC01:
    Type: AWS::EC2::VPC
    Properties: 
      CidrBlock: 10.0.0.0/16
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: MyVPC01

 

# 퍼블릭 서브넷 1 생성
  MyPublicSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref MyVPC01
      AvailabilityZone: !Select [ 0, !GetAZs '' ]
      CidrBlock: 10.0.1.0/24
      MapPublicIpOnLaunch: true
      Tags:
        - Key: Name
          Value: MyPublicSubnet

         
  # 인터넷 게이트웨이 생성
  MyIGW:
    Type: AWS::EC2::InternetGateway
    Properties: 
      Tags:
        - Key: Name
          Value: MyIGW

  # VPC에 인터넷 게이트웨이 연결
  MyIGWattachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      InternetGatewayId: !Ref MyIGW
      VpcId: !Ref MyVPC01

  
  # 퍼블릭 라우팅 테이블 생성
  MyPublicRouting:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref MyVPC01
      Tags:
        - Key: Name
          Value: MyPublicRouting

  # 퍼블릭 서브넷 라우팅 테이블과 연결
  MyPublicSubnetRoutingAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties: 
      RouteTableId: !Ref MyPublicRouting
      SubnetId: !Ref MyPublicSubnet

  # 퍼블릭 기본 라우트 설정
  MyPublicDefault:
    Type: AWS::EC2::Route
    DependsOn: MyIGWattachment
    Properties:
      RouteTableId: !Ref MyPublicRouting
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref MyIGW

  # 퍼블릭 보안 그룹 설정
  MyPublicSecugroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Permit HTTP(80), HTTPS(443), SSH(22)
      VpcId: !Ref MyVPC01
      GroupName: MyPublicSecgroup
      Tags:
        - Key: Name
          Value: MyPublicSecgroup
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0

 # EIP (Elastic IP) 할당
  MyEIP:
    Type: AWS::EC2::EIP
    Properties:
      Domain: vpc
      Tags:
        - Key: Name
          Value: MyEIP

  # NAT Gateway 생성 (퍼블릭 서브넷에 배치)
  MyNAT:
    Type: AWS::EC2::NATGateway
    DependsOn: MyIGWattachment
    Properties:
      AllocationId: !GetAtt MyEIP.AllocationId
      SubnetId: !Ref MyPublicSubnet
      Tags:
        - Key: Name
          Value: MyNAT

  # 프라이빗 서브넷 생성
  MyPrivateSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref MyVPC01
      AvailabilityZone: !Select [ 0, !GetAZs '' ]
      CidrBlock: 10.0.100.0/24
      MapPublicIpOnLaunch: false  # 프라이빗 서브넷에서는 퍼블릭 IP를 할당하지 않음
      Tags:
        - Key: Name
          Value: MyPrivateSubnet
          

  # NAT Gateway를 통한 라우팅을 위한 프라이빗 라우팅 테이블 생성
  MyPrivateRouting:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref MyVPC01
      Tags:
        - Key: Name
          Value: MyPrivateRouting

  # 프라이빗 서브넷 1과 라우팅 테이블 연결
  MyPrivateSubnetRoutingAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties: 
      RouteTableId: !Ref MyPrivateRouting
      SubnetId: !Ref MyPrivateSubnet

  # 프라이빗 기본 라우트 설정 (NAT Gateway 사용)
  MyPrivateDefault:
    Type: AWS::EC2::Route
    DependsOn: MyNAT
    Properties:
      RouteTableId: !Ref MyPrivateRouting
      DestinationCidrBlock: 0.0.0.0/0
      NatGatewayId: !Ref MyNAT

  # 프라이빗 보안 그룹 설정
  MyPrivateSecugroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Permit HTTP(80), HTTPS(443), SSH(22)
      VpcId: !Ref MyVPC01
      GroupName: MyPrivateSecgroup
      Tags:
        - Key: Name
          Value: MyPrivateSecgroup
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0
        - IpProtocol: "icmp"
          CidrIp: 0.0.0.0/0  # 모든 IP에서 ICMP를 허용 (보안을 고려해 제한할 수 있음)
          FromPort: "-1"  # ICMP 타입을 지정하지 않고 모든 타입 허용
          ToPort: "-1"    # ICMP 코드 역시 모든 코드 허용

  # 웹 서버 EC2 인스턴스 1 (프라이빗 서브넷에 배치)
  MyWeb1:
    Type: AWS::EC2::Instance
    DependsOn: MyNAT
    Properties:
      InstanceType: t3.micro
      ImageId: !Ref LatestAmiId
      KeyName: !Ref KeyName
      Tags:
        - Key: Name
          Value: MyWeb1
      NetworkInterfaces: 
        - DeviceIndex: 0
          SubnetId: !Ref MyPrivateSubnet
          GroupSet:
            - !Ref MyPrivateSecugroup
          AssociatePrivateIpAddress: false
          PrivateIpAddress: 10.0.100.100
      UserData:
        Fn::Base64:
          !Sub |
            #!/bin/bash
            export INSTANCE_ID=$(curl -s <http://169.254.169.254/latest/meta-data/instance-id>)
            echo "root:aws1234!" | chpasswd
            sed -i 's/^PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config
            sed -i 's/^#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
            systemctl restart sshd
            dnf -y install httpd
            echo "<h1>${!INSTANCE_ID} (AUTO SCALING) Welcome to AWS WEB Server</h1>" > /var/www/html/index.html
            systemctl enable httpd
            systemctl start httpd

 
Parameters:
  KeyName:
    Description: EC2 KeyPair
    Type: AWS::EC2::KeyPair::KeyName
    ConstraintDescription: EC2 KeyPair
  LatestAmiId:
    Description: EC2 AMI
    Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
    Default: '/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64'
    AllowedValues:
      - /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64

Resources:
  MyVPC01:
    Type: AWS::EC2::VPC
    Properties: 
      CidrBlock: 10.0.0.0/16
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: MyVPC01

  MyIGW:
    Type: AWS::EC2::InternetGateway
    Properties: 
      Tags:
        - Key: Name
          Value: MyIGW

  MyIGWattachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      InternetGatewayId: !Ref MyIGW
      VpcId: !Ref MyVPC01

  MyPublicSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref MyVPC01
      AvailabilityZone: !Select [ 0, !GetAZs '' ]
      CidrBlock: 10.0.1.0/24
      MapPublicIpOnLaunch: true
      Tags:
        - Key: Name
          Value: MyPublicSubnet

  MyPublicRouting:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref MyVPC01
      Tags:
        - Key: Name
          Value: MyPublicRouting

  MyPublicSubnetRoutingAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties: 
      RouteTableId: !Ref MyPublicRouting
      SubnetId: !Ref MyPublicSubnet

  MyPublicDefault:
    Type: AWS::EC2::Route
    DependsOn: MyIGWattachment
    Properties:
      RouteTableId: !Ref MyPublicRouting
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref MyIGW

  MyPublicSecugroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Permit HTTP(80), HTTPS(443), SSH(22)
      VpcId: !Ref MyVPC01
      GroupName: MyPublicSecgroup
      Tags:
        - Key: Name
          Value: MyPublicSecgroup
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0

  MyWeb:
    Type: AWS::EC2::Instance
    DependsOn: MyIGWattachment
    Properties:
      InstanceType: t3.micro
      ImageId: !Ref LatestAmiId
      KeyName: !Ref KeyName
      Tags:
        - Key: Name
          Value: MyWeb
      NetworkInterfaces: 
        - DeviceIndex: 0
          SubnetId: !Ref MyPublicSubnet
          GroupSet:
            - !Ref MyPublicSecugroup
          AssociatePublicIpAddress: true
          PrivateIpAddress: 10.0.1.101
      UserData:
        Fn::Base64:
          !Sub |
            #!/bin/bash
            export INSTANCE_ID=$(curl -s <http://169.254.169.254/latest/meta-data/instance-id>)
            echo "root:aws1234!" | chpasswd
            sed -i 's/^PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config
            sed -i 's/^#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
            sed -i 's/^#PermitRootLogin no/PermitRootLogin yes/' /etc/ssh/sshd_config
            systemctl restart sshd
            dnf -y install httpd
            echo "<h1>${!INSTANCE_ID} (AUTO SCALING) Welcome to AWS WEB Server</h1>" > /var/www/html/index.html
            systemctl enable httpd
            systemctl start httpd

# EIP (Elastic IP) 할당
  MyEIP:
    Type: AWS::EC2::EIP
    Properties:
      Domain: vpc
      Tags:
        - Key: Name
          Value: MyEIP

  # NAT Gateway 생성 (퍼블릭 서브넷에 배치)
  MyNAT:
    Type: AWS::EC2::NATGateway
    DependsOn: MyIGWattachment
    Properties:
      AllocationId: !GetAtt MyEIP.AllocationId
      SubnetId: !Ref MyPublicSubnet
      Tags:
        - Key: Name
          Value: MyNAT

  # 프라이빗 서브넷 생성
  MyPrivateSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref MyVPC01
      AvailabilityZone: !Select [ 0, !GetAZs '' ] // 첫번째 가용영역
      CidrBlock: 10.0.100.0/24
      MapPublicIpOnLaunch: false  # 프라이빗 서브넷에서는 퍼블릭 IP를 할당하지 않음
      Tags:
        - Key: Name
          Value: MyPrivateSubnet
          

  # NAT Gateway를 통한 라우팅을 위한 프라이빗 라우팅 테이블 생성
  MyPrivateRouting:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref MyVPC01
      Tags:
        - Key: Name
          Value: MyPrivateRouting

  # 프라이빗 서브넷 1과 라우팅 테이블 연결
  MyPrivateSubnetRoutingAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties: 
      RouteTableId: !Ref MyPrivateRouting
      SubnetId: !Ref MyPrivateSubnet

  # 프라이빗 기본 라우트 설정 (NAT Gateway 사용)
  MyPrivateDefault:
    Type: AWS::EC2::Route
    DependsOn: MyNAT
    Properties:
      RouteTableId: !Ref MyPrivateRouting
      DestinationCidrBlock: 0.0.0.0/0
      NatGatewayId: !Ref MyNAT

  # 프라이빗 보안 그룹 설정
  MyPrivateSecugroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Permit HTTP(80), HTTPS(443), SSH(22)
      VpcId: !Ref MyVPC01
      GroupName: MyPrivateSecgroup
      Tags:
        - Key: Name
          Value: MyPrivateSecgroup
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0
        - IpProtocol: "icmp"
          CidrIp: 0.0.0.0/0  # 모든 IP에서 ICMP를 허용 (보안을 고려해 제한할 수 있음)
          FromPort: "-1"  # ICMP 타입을 지정하지 않고 모든 타입 허용
          ToPort: "-1"    # ICMP 코드 역시 모든 코드 허용

  # 웹 서버 EC2 인스턴스 1 (프라이빗 서브넷에 배치)
  MyWeb1:
    Type: AWS::EC2::Instance
    DependsOn: MyNAT
    Properties:
      InstanceType: t3.micro
      ImageId: !Ref LatestAmiId
      KeyName: !Ref KeyName
      Tags:
        - Key: Name
          Value: MyWeb1
      NetworkInterfaces: 
        - DeviceIndex: 0
          SubnetId: !Ref MyPrivateSubnet
          GroupSet:
            - !Ref MyPrivateSecugroup
          AssociatePublicIpAddress: false
          PrivateIpAddress: 10.0.100.100
      UserData:
        Fn::Base64:
          !Sub |
            #!/bin/bash
            echo "root:aws1234!" | chpasswd
            sed -i 's/^PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config
            sed -i 's/^#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
            systemctl restart sshd
            dnf -y install httpd
            echo "<h1>Welcome to AWS WEB Server</h1>" > /var/www/html/index.html
            systemctl enable httpd
            systemctl start httpd

 
Parameters:
  KeyName:
    Description: EC2 KeyPair
    Type: AWS::EC2::KeyPair::KeyName
    ConstraintDescription: EC2 KeyPair
  LatestAmiId:
    Description: EC2 AMI
    Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
    Default: '/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64'
    AllowedValues:
      - /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64

Resources:
  MyVPC01:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: MyVPC01

  MyIGW:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - Key: Name
          Value: MyIGW

  MyIGWattachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      InternetGatewayId: !Ref MyIGW
      VpcId: !Ref MyVPC01

  MyPublicSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref MyVPC01
      AvailabilityZone: !Select [0, !GetAZs '']
      CidrBlock: 10.0.1.0/24
      MapPublicIpOnLaunch: true
      Tags:
        - Key: Name
          Value: MyPublicSubnet

  MyPublicRouting:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref MyVPC01
      Tags:
        - Key: Name
          Value: MyPublicRouting

  MyPublicSubnetRoutingAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref MyPublicRouting
      SubnetId: !Ref MyPublicSubnet

  MyPublicDefault:
    Type: AWS::EC2::Route
    DependsOn: MyIGWattachment
    Properties:
      RouteTableId: !Ref MyPublicRouting
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref MyIGW

  MyPublicSecugroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Permit HTTP(80), HTTPS(443), SSH(22)
      VpcId: !Ref MyVPC01
      Tags:
        - Key: Name
          Value: MyPublicSecgroup
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0

  MyWeb:
    Type: AWS::EC2::Instance
    DependsOn: MyIGWattachment
    Properties:
      InstanceType: t3.micro
      ImageId: !Ref LatestAmiId
      KeyName: !Ref KeyName
      Tags:
        - Key: Name
          Value: MyWeb
      NetworkInterfaces:
        - DeviceIndex: 0
          SubnetId: !Ref MyPublicSubnet
          GroupSet:
            - !Ref MyPublicSecugroup
          AssociatePublicIpAddress: true
          PrivateIpAddress: 10.0.1.101
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash
          echo "root:aws1234!" | chpasswd
          sed -i 's/^PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config
          sed -i 's/^#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
          sed -i 's/^#PermitRootLogin no/PermitRootLogin yes/' /etc/ssh/sshd_config
          systemctl restart sshd
          dnf -y install httpd
          echo "<h1>Welcome to AWS WEB Server</h1>" > /var/www/html/index.html
          systemctl enable httpd
          systemctl start httpd

  MyEIP:
    Type: AWS::EC2::EIP
    Properties:
      Domain: vpc
      Tags:
        - Key: Name
          Value: MyEIP

  MyNAT:
    Type: AWS::EC2::NATGateway
    DependsOn: MyIGWattachment
    Properties:
      AllocationId: !GetAtt MyEIP.AllocationId
      SubnetId: !Ref MyPublicSubnet
      Tags:
        - Key: Name
          Value: MyNAT

  MyPrivateSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref MyVPC01
      AvailabilityZone: !Select [0, !GetAZs '']
      CidrBlock: 10.0.100.0/24
      MapPublicIpOnLaunch: false
      Tags:
        - Key: Name
          Value: MyPrivateSubnet

  MyPrivateRouting:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref MyVPC01
      Tags:
        - Key: Name
          Value: MyPrivateRouting

  MyPrivateSubnetRoutingAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref MyPrivateRouting
      SubnetId: !Ref MyPrivateSubnet

  MyPrivateDefault:
    Type: AWS::EC2::Route
    DependsOn: MyNAT
    Properties:
      RouteTableId: !Ref MyPrivateRouting
      DestinationCidrBlock: 0.0.0.0/0
      NatGatewayId: !Ref MyNAT

  MyPrivateSecugroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Permit HTTP(80), HTTPS(443), SSH(22), ICMP
      VpcId: !Ref MyVPC01
      Tags:
        - Key: Name
          Value: MyPrivateSecgroup
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0
        - IpProtocol: icmp
          FromPort: -1
          ToPort: -1
          CidrIp: 0.0.0.0/0

  MyWeb1:
    Type: AWS::EC2::Instance
    DependsOn: MyNAT
    Properties:
      InstanceType: t3.micro
      ImageId: !Ref LatestAmiId
      KeyName: !Ref KeyName
      Tags:
        - Key: Name
          Value: MyWeb1
      NetworkInterfaces:
        - DeviceIndex: 0
          SubnetId: !Ref MyPrivateSubnet
          GroupSet:
            - !Ref MyPrivateSecugroup
          AssociatePublicIpAddress: false
          PrivateIpAddress: 10.0.100.100
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash
          echo "root:aws1234!" | chpasswd
          sed -i 's/^PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config
          sed -i 's/^#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
          sed -i 's/^#PermitRootLogin no/PermitRootLogin yes/' /etc/ssh/sshd_config
          systemctl restart sshd
          dnf -y install httpd
          echo "<h1>Welcome to AWS WEB Server</h1>" > /var/www/html/index.html
          systemctl enable httpd
          systemctl start httpd

'IT 엔지니어 > CLOUD' 카테고리의 다른 글

AWS - terraform -2  (0) 2025.06.10
AWS - NLB  (0) 2025.06.10
AWS - Auto Scaling Group  (1) 2025.06.09
AWS - RDS / VPC -  (0) 2025.06.08
AWS - RDS  (0) 2025.06.08