Skip to main content

실습용 윈도우 EC2 인스턴스 자동화

본 문서가이드실습을AWS 위해CLI를 사용하여 윈도우 서버 EC2 인스턴스를 여러 개 준비자동으로 설정하는 과정을 AWS CLI로 자동화하는 과정을상세히 설명합니다. 실제 환경에서는 사용자의 요구사항에 맞게 설정을 변경조정해야 하며 반드시, 실제 테스트가 반드시 필요합니다. 따라서 본 문서를 참고로 봐주시면 좋겠습니다.

사전

요구사항

    내용은
  • AWS CLI를CLI 사용하게되며,설치 및 구성
  • Bash 스크립트에 대한 기 지식
  • AWS 계정 및 필요합니다. 일부권한
  • 과정은
콘솔로도 진행이 가능합니다.

 

전체적인 워크플로우

다음과
    같습니다.

  1. 초기

    EC2 인스턴스 실행

  2. >
  3. 윈도우 인스턴스에 접속하여 필요한 프로그램 설치
  4. > Custom
  5. 커스텀 AMI 생성
  6. >
  7. 커스텀 CustomAMI를 AMI 생성 후이용해 필요한 만큼 인스턴스 실행
  8. >
  9. 결과 CSV 파일 확인

  10.  

     

 

상세 과정

1. 초기 EC2 인스턴스 실행

콘솔먼저, 또는 아래 명령어를 사용해서 사용자 지정커스텀 AMI를 만들기 위한 인스턴스를 실행합니다. 이때다음 --image-idAWS CLI 윈도우 OS에 해당하는 AMI를 넣을 수 있습니다. --instance-type, --key-name, --security-group-ids, --subnet-id는 모두명령어를 사용자에 맞게 수정해야 합니다.하세요:

aws ec2 run-instances \
  --image-id ami-04df9ee4d3dfde202 \
  --instance-type m5.large \
  --key-name brandon-demo-us-east-1your-key-pair-name \
  --security-group-ids sg-07384c7c539519006your-security-group-id \
  --subnet-id subnet-051342beabe221da6your-subnet-id \
  --count 1 \
  --associate-public-ip-address


주의: --image-id, --instance-type, --key-name, --security-group-ids, --subnet-id를 사용자의 환경에 맞게 수정하세요.

윈도우 접속하여 필요한 프로그램 설치

여기서는 RDP를 통해

2. 윈도우 인스턴스에 접속 및 프로그램 설치

RDP를 사용 되겠습윈도우 인스턴스에 접속한 후, 필요한 프로그램을 설치합니다.

3.

 

Custom커스텀 AMI 생성

콘솔로 AMI를 생성합니. 또는 아래의 Bash 스크립트를 용하여 준비된 인턴스에 대한 Custom AMI를 생성할 수 있습니다.:

#!/bin/bash

# Function to create AMI and생성 return the AMI ID함수
create_ami() {
    local instance_id=$1
    local ami_name=$2
    local ami_description=$3

    aws ec2 create-image \
        --instance-id "$instance_id" \
        --name "$ami_name" \
        --description "$ami_description" \
        --no-reboot \
        --query 'ImageId' \
        --output text
}

# Function to check AMI status상태 확인 함수
check_ami_status() {
    local ami_id=$1
    aws ec2 describe-images \
        --image-ids "$ami_id" \
        --query 'Images[0].State' \
        --output text
}

# Main메인 script스크립트
echo "Enter인스턴스 theID를 Instance ID:입력하세요:"
read instance_id

echo "Enter aAMI의 name이름을 for the new AMI:입력하세요:"
read ami_name

echo "Enter aAMI의 description설명을 for the new AMI:입력하세요:"
read ami_description

echo "CreatingAMI AMI.생성 중..."
ami_id=$(create_ami "$instance_id" "$ami_name" "$ami_description")

echo "AMI creation생성이 initiated.시작되었습니다. AMI ID: $ami_id"
echo "WaitingAMI가 for사용 AMI가능할 to때까지 be대기 available.중..."

while true; do
    status=$(check_ami_status "$ami_id")
    if [ "$status" = "available" ]; then
        echo "AMIAMI가 is사용 now available.가능합니다."
        break
    elif [ "$status" = "failed" ]; then
        echo "AMI creation생성에 failed.실패했습니다."
        exit 1
    else
        echo "Current현재 status:상태: $status. Checking30초 again in다시 30 seconds.확인합니다..."
        sleep 30
    fi
done

echo "Final최종 AMI ID: $ami_id"

4.

커스텀

필요AMI를 이용만큼다수의 인스턴스 실행

주의사항

  • 사전에 EC2 인스턴스 Quota가 충분한지 확인합니.
  • 가용영역 (AZ)에 가용한 인스턴스가 부족할 경우 문제가 생길 수 있습니다.

--image-id, --instance-type, --key-name, --security-group-ids, --subnet-id, --priv-launch-key

를 모두 사용자에 알맞게 수정합니다.

그리고 Bash 스크립트를 실행사용하여 작업을커스텀 수행합니다.

AMI로부터

이때 입력으로 2가지를 받습니다.

  • 앞에서 최초로 Custom AMI 만들때 사용되었던여러 인스턴스에서의 윈도우 접속 비밀번호입력해야실행하고 설정할 수 있습니다.
  • 실행을 원하는 인스턴스의 수를 입력합니다.
:

#!/bin/bash

# Function랜덤 to비밀번호 generate생성 a random password함수
generate_password() {
    openssl rand -base64 12
}

# Function인스턴스 to실행 launch an instance and return its ID함수
launch_instance() {
    local instance_number=$1
    local initial_password=$2
    aws ec2 run-instances \
        --image-id ami-04df9ee4d3dfde202your-custom-ami-id \
        --count 1 \
        --instance-type m5.large \
        --key-name YourKeyPairyour-key-pair-name \
        --security-group-ids sg-xxxxxxxxxxxxxxxxxyour-security-group-id \
        --subnet-id subnet-xxxxxxxxxxxxxxxxxyour-subnet-id \
        --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=WindowsInstance-'$instance_number'}]' \
        --user-data "<powershell>net user Administrator '${initial_password}'</powershell>" \
        --query 'Instances[0].InstanceId' \
        --output text
}

# Function to get public공개 IP of가져오기 an instance함수
get_public_ip() {
    local instance_id=$1
    aws ec2 describe-instances \
        --instance-ids $instance_id \
        --query 'Reservations[0].Instances[0].PublicIpAddress' \
        --output text
}

# FunctionSSM을 to사용한 change비밀번호 password변경 using SSM함수
change_password() {
    local instance_id=$1
    local new_password=$2
    aws ssm send-command \
        --instance-ids "$instance_id" \
        --document-name "AWS-RunPowerShellScript" \
        --parameters "commands=[\"net user Administrator '${new_password}'\"]" \
        --output text
}

# Ask초기 for비밀번호 the입력 initial password받기
read -s -p "Enter모든 the인스턴스의 initial초기 password비밀번호를 for all instances:입력하세요: " INITIAL_PASSWORD
echo

# Ask생성할 for인스턴스 the number입력 of instances받기
read -p "Enter생성할 the인스턴스 number수를 of instances to create:입력하세요: " INSTANCE_COUNT

# Prepare CSV file파일 준비
echo "Instance ID,Public IP,Username,Password" > rdp_info.csv

# Launch인스턴스 instances실행
echo "Launching $INSTANCE_COUNT instances.개의 인스턴스를 실행 중..."
instance_ids=()
for i in $(seq 1 $INSTANCE_COUNT); do
    instance_id=$(launch_instance $i "$INITIAL_PASSWORD")
    instance_ids+=($instance_id)
    echo "Launched instance인스턴스 $i:i 실행됨: $instance_id"
done

# Wait인스턴스 for실행 instances대기 to be추가 running5분 and 5 minutes extra대기
echo "Waiting인스턴스가 for실행되고 instances안정화될 to때까지 be대기 running and stabilize.중..."
aws ec2 wait instance-running --instance-ids "${instance_ids[@]}"
echo "Instances인스턴스가 are실행 running.중입니다. Waiting완전한 an초기화를 additional위해 5추가로 minutes5분 for full initialization.대기합니다..."
sleep 300

# Process each인스턴스 instance처리
for instance_id in "${instance_ids[@]}"; do
    echo "Processing인스턴스 instance:처리 중: $instance_id"
    
    # Get public공개 IP 가져오기
    public_ip=$(get_public_ip $instance_id)
    
    # Generate new비밀번호 password생성
    new_password=$(generate_password)
    
    # Change비밀번호 password변경
    echo "Changing password for instance인스턴스 $instance_id.instance_id의 비밀번호 변경 중..."
    change_password "$instance_id" "$new_password"
    
    # AddCSV에 to CSV추가
    echo "$instance_id,$public_ip,Administrator,$new_password" >> rdp_info.csv
    
    echo "Instance인스턴스 $instance_id processed"처리 완료"
done

echo "All모든 instances인스턴스가 launched실행되고 and processed.처리되었습니다. RDP information saved in정보가 rdp_info.csv"csv 파일에 저장되었습니다."
echo "Note:주의: Passwords비밀번호가 have무작위로 been생성된 changed to비밀번호로 randomly generated passwords.변경되었습니다."

주의사항:

  • 스크립트 실행 전 EC2 인스턴스 할당량이 충분한지 확인하세요.
  • 선택한 가용 영역(AZ)에 충분한 인스턴스 용량이 있는지 확인하세요.
  • --image-id, --instance-type, --key-name, --security-group-ids, --subnet-id를 사용자의 환경에 맞게 수정하세요.

5. 결과 CSV 파일 확인

스크립트 실행이 완료되면 rdp_info.csv 파일에 각 인스턴스의 접속 정보가 저장됩니다. 이 파일을 안전하게 보관하세요.

결론

이 가이드를 통해 AWS CLI를 사용하여 윈도우 EC2 인스턴스를 자동으로 설정하는 방법을 배웠습니다. 이 과정을 통해 다수의 윈도우 인스턴스를 효율적으로 관리할 수 있습니다. 하지만 실제 환경에 적용하기 전에 반드시 테스트를 진행하고, 보안 설정을 신중히 검토해야 합니다.

추가 질문이나 도움이 필요하다면 언제든 문의해주세요!