I got IT

AWS EC2 Userdata (유저데이터) 본문

AWS

AWS EC2 Userdata (유저데이터)

joshhoxy 2023. 5. 12. 15:30

AWS EC2 Userdata 란 ?

AWS Userdata는 EC2를 생성할 때 실행되는 스크립트로서 인스턴스를 초기 세팅할 때 유용하게 사용할 수 있습니다.

정형화된 유저데이터를 사용하게 되면 서버를 초기 세팅할 때 서버에 직접 연결하여 명령문을 일일히 실행하지 않아도 되서 굉장히 편리하고 여러대의 인스턴스를 생성할 때 작업속도를 향상 시킬 수 있습니다.

Userdata 사용 용도

예를 들어, EC2 인스턴스를 시작할 때 유저데이터를 사용하여 웹 서버를 설치하고, 애플리케이션을 배포하거나, 로깅 설정을 구성하거나, 사용자 정의 스크립트를 실행하는 등의 작업을 수행할 수 있습니다.

 

OS User 설정 

서버 초기 세팅 시 RBAC를 위하여 사용자별로 권한을 분리하여야 합니다. 이 때 유저데이터를 활용하여 EC2를 생성할 때,유저를 생성하고 특정 권한을 부여하는 작업을 자동으로 수행할 수 있습니다. 

 

패키지 설치 

서버 구성 시 필요한 패키지를 인스턴스 생성과 동시에 설치할 수 있습니다. 

예를들어 웹서버 인스턴스를 생성하는 경우 yum install -y httpd 명령어를 실행하도록 하여 웹서버를 빠르게 구축할 수 있습니다.

또, CloudWatch Agent나 CodeDeploy를 이용하는 경우 서버에 접속하여 일일히 설치할 필요 없이 유저데이터로 실행시켜 빠르게 에이전트 파일을 설치 및 구성할 수 있습니다. 

Userdata로 CWAgent를 구성하는 방법은 다음 포스팅에서 설명하도록 하겠습니다. 🔗

 

Userdata 사용 방법

EC2 Userdata를 사용하는 방법을 AWS Console 화면을 통해 설명하겠습니다.

 

0. EC2 기본 구성 설정에 대한 옵션을 선택합니다. 

1. EC2 시작 페이지에서 고급 세부 정보 토글을 활성화 하여 줍니다.

2. 사용자 데이터 필드에 쉘스크립트 추가

아래로 쭉쭉 내려가서 사용자 데이터 필드에 실행할 스크립트 코드를 작성해줍니다.

- useradd : 사용자 추가

- usermod -G: wheel 그룹에 josh 추가. wheel 그룹은 admin 그룹임

- passwd 설정

- 패스워드로 SSH 접근 허용 

- 추가: passwd --expire josh 명령어는 사용자가 최초 로그인 시 비밀번호를 변경하도록 강제 설정

 

3. 인스턴스 시작 

인스턴스 시작 버튼을 눌러 인스턴스를 생성해 줍니다. 

위 예시와 같은 코드 사용 시 AWS 키페어가 없어도 user/pw 인증으로 SSH 연결을 생성할 수 있습니다.

* 당연히 SSH 인바운드 보안그룹은 열어주세요!

Userdata 예시

1. OS User 추가 및 설정

#!/bin/bash
useradd -u 2001 josh 
usermod -G wheel josh
echo "passwd12#$" | passwd --stdin passwd12#$
sed -i 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config
systemctl restart sshd

# passwd --expire sysadmin (로그인 시 비밀번호 초기화)

 

2. 웹 서버 구축

#!/bin/bash
yum update -y
yum install -y httpd.x86_64
systemctl start httpd.service
systemctl enable httpd.service
echo "Hello World from $(hostname -f)" > /var/www/html/index.html

Userdata 실행 시 shell을 통해 stdin 입력할 수 없으므로 패키지를 설치할 때 -y 옵션을 지정하는 것을 까먹지 않도록 주의합니다.

 

3. CWAgent 설치

sudo yum install amazon-cloudwatch-agent -y

에이전트 설치 후 어떤 지표를 수집할 지에 대한 구성 설정은 JSON 형태의 config 파일로 설정하거나 설치 Wizard를 통해 가능합니다.

수동으로 Manually 작성하는 방법은 다음에 포스팅 하도록 하겠습니다.

 

4. CodeDeploy Agent 설치

#!/bin/bash -xe

## Code Deploy Agent Bootstrap Script##


exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
AUTOUPDATE=false

function installdep(){

if [ ${PLAT} = "ubuntu" ]; then

  apt-get -y update
  # Satisfying even ubuntu older versions.
  apt-get -y install jq awscli ruby2.0 || apt-get -y install jq awscli ruby



elif [ ${PLAT} = "amz" ]; then
  yum -y update
  yum install -y aws-cli ruby jq

fi

}

function platformize(){

#Linux OS detection#
 if hash lsb_release; then
   echo "Ubuntu server OS detected"
   export PLAT="ubuntu"


elif hash yum; then
  echo "Amazon Linux detected"
  export PLAT="amz"

 else
   echo "Unsupported release"
   exit 1

 fi
}


function execute(){

if [ ${PLAT} = "ubuntu" ]; then

  cd /tmp/
  wget https://aws-codedeploy-${REGION}.s3.amazonaws.com/latest/install
  chmod +x ./install

  if ./install auto; then
    echo "Installation completed"
      if ! ${AUTOUPDATE}; then
            echo "Disabling Auto Update"
            sed -i '/@reboot/d' /etc/cron.d/codedeploy-agent-update
            chattr +i /etc/cron.d/codedeploy-agent-update
            rm -f /tmp/install
      fi
    exit 0
  else
    echo "Installation script failed, please investigate"
    rm -f /tmp/install
    exit 1
  fi

elif [ ${PLAT} = "amz" ]; then

  cd /tmp/
  wget https://aws-codedeploy-${REGION}.s3.amazonaws.com/latest/install
  chmod +x ./install

    if ./install auto; then
      echo "Installation completed"
        if ! ${AUTOUPDATE}; then
            echo "Disabling auto update"
            sed -i '/@reboot/d' /etc/cron.d/codedeploy-agent-update
            chattr +i /etc/cron.d/codedeploy-agent-update
            rm -f /tmp/install
        fi
      exit 0
    else
      echo "Installation script failed, please investigate"
      rm -f /tmp/install
      exit 1
    fi

else
  echo "Unsupported platform ''${PLAT}''"
fi

}

platformize
installdep
REGION=$(curl -s 169.254.169.254/latest/dynamic/instance-identity/document | jq -r ".region")
execute