1. 로컬 PC에서 Vagrant로 CentOS 가상환경 띄우기

설치 환경

  • Macbook Pro Intel (2019)
  • CentOS 7.9

 

설치 스크립트

#!/usr/bin/env bash

directory="$HOME/workspace/VM/centos7"
ssh_key_file="$HOME/.ssh/id_rsa"

# Check if Homebrew is installed
if ! [ -x "$(command -v brew)" ]; then
  echo '>> Homebrew is not installed.' >&2
  /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
fi

# Check if VirtualBox is installed
if ! [ -x "$(command -v vboxmanage)" ]; then
  echo '>> VirtualBox is not installed.' >&2
  brew install --cask virtualbox
fi

# Check if VirtualBox Extension Pack is installed
if ! vboxmanage list extpacks | grep "Oracle VM VirtualBox Extension Pack"; then
  echo '>> VirtualBox Extension Pack is not installed.'
  rm Oracle_VM_VirtualBox_Extension_Pack-$(VBoxManage -v | cut -d r -f 1).vbox-extpack
fi

# Check if Vagrant is installed
if ! [ -x "$(command -v vagrant)" ]; then
  echo '>> Vagrant is not installed.' >&2
  brew install vagrant
fi

# Check if Ansible is installed
if ! [ -x "$(command -v ansible)" ]; then
  echo '>> Ansible is not installed.' >&2
  brew install ansible
fi

# Create directory for CentOS VM
if [ ! -d "$directory" ]
then
    mkdir -p "$directory"
fi

cd "$directory"

# Check if the required Vagrant plugins are installed
if ! vagrant plugin list | grep -q vagrant-vbguest
then
    echo ">> vagrant-vbguest plugin is not installed."
    vagrant plugin install vagrant-vbguest
fi

if ! vagrant plugin list | grep -q vagrant-disksize
then
    echo ">> vagrant-disksize plugin is not installed."
    vagrant plugin install vagrant-disksize
fi

# Initialize Vagrantfile
vagrant init

# Edit Vagrantfile
cat << EOF > Vagrantfile
ENV["LC_ALL"] = "en_US.UTF-8"
Vagrant.configure("2") do |centos|

  # All servers will run cent 7
  centos.vm.box = "centos/7"
  centos.vm.box_check_update = false
  centos.disksize.size = "60GB"

  # Create the cent1 Server
  N = 1
  (1..N).each do |i|
    hostname = "cent7-#{i}"
    centos.vm.define hostname do |host1|
      host1.vm.hostname = hostname
      host1.vm.network "private_network", ip: "192.168.56.#{10 + i}"
      host1.vbguest.auto_update = false
      host1.vm.provider "virtualbox" do |v|
        v.name = hostname
        v.memory = "2048"
        v.cpus = "2"
        v.linked_clone = "true"
        v.gui = "false"
        v.customize ['modifyvm', :id, '--graphicscontroller', 'vmsvga']
        v.customize ['modifyvm', :id, '--vram', '20']
      end
    end
  end

  # Provision with Ansible playbook
  centos.vm.provision "ansible" do |ansible|
    ansible.playbook = "init.yml"
  end
end
EOF

# Edit Ansible playbook
cat << EOF > init.yml
- name: init.yml
  hosts: all
  gather_facts: no
  become: yes
  tasks:
    - name: Create users
      user:
        name: "{{ item }}"
        shell: /bin/bash
        home: "/home/{{ item }}"
        generate_ssh_key: true
        password_lock: yes
      with_items:
        - irteam
        - irteamsu
        - centos
    - name: Add sudoers.d file
      copy:
        content: |
          %{{item}} ALL=(ALL) NOPASSWD: ALL
        dest: "/etc/sudoers.d/{{item}}"
        owner: root
        group: root
        mode: 0440
        validate: "/usr/sbin/visudo -c -f '%s'"
      with_items:
        - irteam
        - irteamsu
        - centos
    - name: Add SSH key
      authorized_key:
        user: "{{ item }}"
        state: present
        key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}"
      with_items:
        - irteam
        - irteamsu
        - centos
        - vagrant
        - root
    - name: Restart SSH service
      ansible.builtin.systemd:
        state: restarted
        name: sshd.service
EOF

# Start Vagrant VM
vagrant up

# Generate SSH key
if [[ ! -f "$ssh_key_file" ]]; then
    echo ">> Generating new SSH key..."
    ssh-keygen
fi

cat ~/.ssh/id_rsa.pub

cd "$directory"

# SSH into Vagrant VM
vagrant SSH

vagrant ssh -c "cat ~/.ssh/authorized_keys"

vagrant ssh -c 'exit'

# Print public SSH key
cat "$ssh_key_file"

# Provision Vagrant VM
vagrant provision

# Connect
ssh-keyscan -H 192.168.56.11 >> ~/.ssh/known_hosts
ssh -o StrictHostKeyChecking=no centos@192.168.56.11

 

결과

성공!

 

 

2. Ubuntu 인스턴스에서 Vagrant로 CentOS 가상환경 띄우기

설치 환경

  • NHN Cloud
  • Ubuntu 20.04 LTS
  • CentOS 7.9

 

설치 스크립트

#!/usr/bin/env bash

directory="$HOME/workspace/VM/centos7"
ssh_key_file="$HOME/.ssh/id_rsa"

# Check if wget is installed
if ! command -v wget &> /dev/null
then
    echo ">> wget is not installed."
    sudo apt-get update
    sudo apt-get install -y wget
fi

# Download and add VirtualBox public key

# Add VB repo to package manager

# Update package list
sudo apt-get update

# Install VirtualBox
sudo apt-get install -y virtualbox-6.1

# Clean up
#sudo apt-get autoremove
#sudo apt-get autoclean


# Check if VirtualBox Extension Pack is installed
if ! vboxmanage list extpacks | grep -q "Oracle VM VirtualBox Extension Pack"; then
  echo '>> VirtualBox Extension Pack is not installed.'
  wget https://download.virtualbox.org/virtualbox/6.1.42/Oracle_VM_VirtualBox_Extension_Pack-6.1.42.vbox-extpack
  rm "Oracle_VM_VirtualBox_Extension_Pack-6.1.42.vbox-extpack"
fi

# Check if Vagrant is installed
if ! [ -x "$(command -v vagrant)" ]; then
  echo '>> Vagrant is not installed.' >&2
  wget -O- https://apt.releases.hashicorp.com/gpg | gpg --dearmor | sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg
  sudo apt update && sudo apt install -y vagrant
fi

# Check if Ansible is installed
if ! [ -x "$(command -v ansible)" ]; then
  echo '>> Ansible is not installed.' >&2
  sudo apt install -y ansible
fi

# Create directory for CentOS VM
if [ ! -d "$directory" ]
then
    mkdir -p "$directory"
fi

cd "$directory"

# Check if the required Vagrant plugins are installed
if ! vagrant plugin list | grep -q vagrant-vbguest
then
    echo ">> vagrant-vbguest plugin is not installed."
    vagrant plugin install vagrant-vbguest
fi

if ! vagrant plugin list | grep -q vagrant-disksize
then
    echo ">> vagrant-disksize plugin is not installed."
    vagrant plugin install vagrant-disksize
fi

# Initialize Vagrantfile
vagrant init

# Edit Vagrantfile
cat << EOF > Vagrantfile
ENV["LC_ALL"] = "en_US.UTF-8"
Vagrant.configure("2") do |centos|

  # All servers will run cent 7
  centos.vm.box = "centos/7"
  centos.vm.box_check_update = false
  centos.disksize.size = "60GB"

  # Create the cent1 Server
  N = 1
  (1..N).each do |i|
    hostname = "cent7-#{i}"
    centos.vm.define hostname do |host1|
      host1.vm.hostname = hostname
      host1.vm.network "private_network", ip: "192.168.56.#{10 + i}"
      host1.vbguest.auto_update = false
      host1.vm.provider "virtualbox" do |v|
        v.name = hostname
        v.memory = "2048"
        v.cpus = "2"
        v.linked_clone = "true"
        v.gui = "false"
        v.customize ['modifyvm', :id, '--graphicscontroller', 'vmsvga']
        v.customize ['modifyvm', :id, '--vram', '20']
      end
    end
  end

  # Provision with Ansible playbook
  centos.vm.provision "ansible" do |ansible|
    ansible.playbook = "init.yml"
  end
end
EOF

# Edit Ansible playbook
cat << EOF > init.yml
- name: init.yml
  hosts: all
  gather_facts: no
  become: yes
  tasks:
    - name: Create users
      user:
        name: "{{ item }}"
        shell: /bin/bash
        home: "/home/{{ item }}"
        generate_ssh_key: true
        password_lock: yes
      with_items:
        - irteam
        - irteamsu
        - centos
    - name: Add sudoers.d file
      copy:
        content: |
          %{{item}} ALL=(ALL) NOPASSWD: ALL
        dest: "/etc/sudoers.d/{{item}}"
        owner: root
        group: root
        mode: 0440
        validate: "/usr/sbin/visudo -c -f '%s'"
      with_items:
        - irteam
        - irteamsu
        - centos
    - name: Add SSH key
      authorized_key:
        user: "{{ item }}"
        state: present
        key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}"
      with_items:
        - irteam
        - irteamsu
        - centos
        - vagrant
        - root
    - name: Restart SSH service
      ansible.builtin.systemd:
        state: restarted
        name: sshd.service
EOF

# Start Vagrant VM
vagrant up

# Generate SSH key
if [[ ! -f "$ssh_key_file" ]]; then
    echo ">> Generating new SSH key..."
    ssh-keygen
fi

cat ~/.ssh/id_rsa.pub

cd "$directory"

# SSH into Vagrant VM
vagrant SSH

vagrant ssh -c "cat ~/.ssh/authorized_keys"

vagrant ssh -c 'exit'

# Print public SSH key
cat "$ssh_key_file"

# Provision Vagrant VM
vagrant provision

# Connect
#ssh centos@192.168.56.11
ssh-keyscan -H 192.168.56.11 >> ~/.ssh/known_hosts
ssh -o StrictHostKeyChecking=no centos@192.168.56.11

 

결과

실패..

 

에러 상황

  • NHN 클라우드 ubuntu 인스턴스에서 vagrant로 centos 가상환경을 띄우려고 함
  • vagrant up 단계에서 에러가 발생해 다음 단계로 넘어가지 못 함

There was an error while executing `VBoxManage`, a CLI used by Vagrant
for controlling VirtualBox. The command and stderr is shown below.

Command: ["startvm", "d7c9b9b1-a0d1-4ff2-b119-3a33f10a1540", "--type", "gui"]

Stderr: VBoxManage: error: The virtual machine 'cent7-1' has terminated unexpectedly during startup because of signal 6
VBoxManage: error: Details: code NS_ERROR_FAILURE (0x80004005), component MachineWrap, interface IMachine

 

시도해본 방법

  • 호스트 재부팅 - 실패
  • virtualbox와 virtualbox extension pack 버전 맞추기 - 실패
  • VM headless 모드로 시작 - 시도 전

 

결론

설치를 진행하고 있는 ubuntu 자체가 인스턴스 환경이어서 그 위에 또 가상환경(VM)을 띄우는게 불가능한 것으로 판단..

vagrant 대신 호스트 OS 위에 하이퍼바이저를 띄우지 않는 구조인 docker로 진행하기로 결정!

1. CentOS에 PostgreSQL 설치

설치 환경

  • NHN Cloud 인스턴스 또는 Docker 컨테이너
  • CentOS 7.9

 

Workflow

  1. 스크립트 실행시 설치하고자 하는 버전이 입력되었는지 확인
  2. 설치하고자 하는 PC의 OS, 아키텍처가 적합한지 확인
  3. CentOS 7인지 확인
  4. PostgreSQL이 이미 설치된 경우 제거
  5. 필요한 패키지 설치 및 yum 레포지토리 업데이트
  6. PostgreSQL 설치
  7. 초기화 및 유저 비밀번호 설정
  8. 외부 접속을 위한 pg_hba.conf와 postgresql.conf 수정 및 재시작
  9. PostgreSQL 실행

 

설치 스크립트

#!/usr/bin/env bash

# 설치하고자 하는 버전
version=$1
major_version=${version%%.*}  # 15.2 -> 15

# 설치하려는 버전 번호를 받았는지 확인
if [ $# -eq 0 ]; then
    echo -e "\033[31;1m>> Error: Version number is missing. Usage: ./install_postgres_yum.sh <version>\033[0m"
    exit 1
fi

# OS가 Linux x86_64인지 확인
if [ "$(uname -s)" != "Linux" ]; then
    echo -e "\033[31;1m>> Error: Your OS is not supported.\033[0m"
    exit 1
fi
if [ "$(uname -m)" != "x86_64" ]; then
    echo -e "\033[31;1m>> Error: Your architecture is not supported.\033[0m"
    exit 1
fi

# CentOS가 Enterprise Linux 7 (EL7)인지 확인
if [ "$(rpm -q --queryformat '%{VERSION}' centos-release)" != "7" ]; then
    echo -e "\033[31;1m>> Error: This script is only compatible with Enterprise Linux 7 (EL7)\033[0m"
    exit 1
fi

# PostgreSQL이 이미 설치되어 있다면 제거
if yum list installed | grep postgresql; then
    echo -e "\033[31;1m>> Remove PostgreSQL already installed...\033[0m"
    sudo yum -y remove postgresql*
fi

# 필요한 패키지 설치
echo -e "\033[31;1m>> Install required packages...\033[0m"
yum install -y sudo
sudo yum -y update
sudo yum install -y epel-release
sudo yum install -y zstd

# PostgreSQL 설치
echo -e "\033[31;1m>> Install PostgreSQL...\033[0m"
sudo yum install -y https://download.postgresql.org/pub/repos/yum/${major_version}/redhat/rhel-7-x86_64/postgresql${major_version}-libs-${version}-1PGDG.rhel7.x86_64.rpm
sudo yum install -y https://download.postgresql.org/pub/repos/yum/${major_version}/redhat/rhel-7-x86_64/postgresql${major_version}-${version}-1PGDG.rhel7.x86_64.rpm
sudo yum install -y https://download.postgresql.org/pub/repos/yum/${major_version}/redhat/rhel-7-x86_64/postgresql${major_version}-server-${version}-1PGDG.rhel7.x86_64.rpm

# 초기화
echo -e "\033[31;1m>> Initialize PostgreSQL...\033[0m"
sudo /usr/pgsql-${major_version}/bin/postgresql-${major_version}-setup initdb

# 시작
echo -e "\033[31;1m>> Start PostgreSQL...\033[0m"
sudo systemctl start postgresql-${major_version}
sudo systemctl enable postgresql-${major_version}

# 유저 생성
username="postgres"
password="nhnpostgres123"

sudo adduser $username
echo "$username:$password" | sudo chpasswd

# postgres user로 변경 후 설정파일 수정
echo -e "\033[31;1m>> Edit pg_hba.conf and postgresql.conf\033[0m"
sudo su - postgres <<EOF
    echo "host    all             all             133.186.251.35/22       md5" >> /var/lib/pgsql/${major_version}/data/pg_hba.conf

    sed -i "s/#listen_addresses = 'localhost'/listen_addresses = '*'/g" /var/lib/pgsql/${major_version}/data/postgresql.conf

    exit
EOF

# 재시작
echo -e "\033[31;1m>> Restart PostgreSQL...\033[0m"
sudo systemctl restart postgresql-${major_version}

# 실행
echo -e "\033[31;1m>> Run PostgreSQL...\033[0m"
sudo su - postgres -c "psql"

 

IaaS vs. SaaS vs. PaaS

요즘, 클라우드 하면 IaaS, PaaS, SaaS 를 많이 들어보셨을텐데, 이는 클라우드 서비스를 분야별 특성으로 나눈 것입니다.

 

IaaS, PaaS, SaaS가 대체 무엇인지 비교를 통해 알아보겠습니다.

IaaS (Infrastructure-as-a-service)

시스템 인프라를 서비스로서 제공합니다. 네트워크, 스토리지, 서버 등을 가상화하여 제공하고 관리합니다. 즉, 가상머신을 빌려주는 서비스입니다.

NHN Cloud, AWS, MS Azure, GCE 등에서 제공합니다.

 

PaaS (Platform-as-a-service)

애플리케이션 실행 환경을 서비스로서 제공합니다. 소프트웨어 작성을 위한 플랫폼을 가상화하여 제공하고 관리합니다. 개발자는 운영체제, 소프트웨어 업데이트, 저장소 또는 인프라에 대한 관리없이 소프트웨어 개발에만 집중할 수 있습니다.

NHN Cloud PaaS-TA, AWS Elastic Beanstalk, Heroku, Google App Engine 등이 있습니다.

 

SaaS (Software-as-a-service)

애플리케이션을 서비스로서 제공합니다. 대부분의 SaaS 애플리케이션 웹 브라우저를 통해 직접 실행되므로 클라이언트 측에서 다운로드 설치가 필요하지 않습니다.

NHN Cloud Dooray!, Google Apps, Dropbox 등이 있습니다.

 

 

NHN Cloud

국내 NCP 중 하나인 NHN Cloud는 IaaS, PaaS, SaaS를 모두 아우르는 전 영역에서 각 산업 분야에 맞는 클라우드 솔루션을 직접 개발 및 출시하여 사업영역을 확장해나가고 있습니다.

 

NHN Cloud의 서비스를 나누어 보면 다음과 같습니다.

 

IaaS

  • Public Cloud
  • Private Cloud
  • Multi Cloud

 

PaaS

  • PaaS-TA

애플리케이션 개발과 운영을 위해 필요한 플랫폼을 온라인 환경에서 제공하는 공개형 PaaS 플랫폼입니다. 인프라 제어 및 관리 환경, 실행 환경, 개발 환경, 서비스 환경, 운영 환경으로 구성되며, 다양한 개발 언어와 프레임워크를 제공합니다.

국내 최초로 공공 클라우드 PaaS 부문 보안인증을 획득했습니다.

  • Gamebase
  • Security
  • Notification
  • Search
  • Dev Tools
  • 등등

 

SaaS

  • Dooray! : 메일과 프로젝트 단위의 업무 관리, 메신저를 통합한 협업도구
  • 그룹웨어 : 전자결재 및 게시판을 통합
  • ERP : 인사와 재무 서비스를 제공하는 ERP

 

 

 

 

참고링크

가상화 (Virtualization)

가상화란?

쉽게 말하면, 물리적인 하드웨어를 논리적으로 구분하는 것

 

서버의 CPU와 메모리 등의 자원을 최대한 활용할 수 있는 방법을 생각했을 때, 간단하게 생각하면 동시에 여러 개의 서버를 한번에 올리면 되지 않을까 싶다. 하지만, 서로 영향을 받게 되고, 보안 문제나 서버가 다운되면 모든 서비스가 중단되는 위험이 있다. 그래서 가상화의 개념이 등장하였다.

 

VM과 컨테이너

가상화의 핵심은 Isolation이다. 논리적으로 격리가 제대로 이루어지면, 각각의 가상 환경에서 문제가 생겨도, 다른 영역에 영향을 미치지 않는다.

 

가상화는 크게 2가지 유형으로 나뉘는데, 가상머신(vm)과 컨테이너(container)이다. 클라우드 환경에서 서비스를 운영하고자 한다면 꼭 알아두어야 하는 개념이다.

가상화 관점에서 두 개의 차이점을 간단하게 설명하자면, 가상머신은 하이퍼바이저를 이용하여 리소스 전체를 가상화하는 방법이고, 컨테이너는 OS 수준에서 프로세스를 컨테이너 형태로 격리하는 방법이다.

 

두 방식은 차이점이 확실하여 그에 따른 장단점도 분명하기 때문에, 각각의 기술에 대한 배경과 철학을 이해하면 좋을 것이다. 이번에는 하이퍼바이저 가상화에 대해 다루어보겠다.

 

 

하이퍼바이저 (Hypervisor)

하이퍼바이저란?

가상화에서 계속 하이퍼바이저라는 단어를 언급했는데, 하이퍼바이저란 대체 무엇일까?

 

  • 가상 머신(VM)을 생성하고 구동하는 소프트웨어
  • 가상 머신 모니터(VMM)라고도 불림
  • 하이퍼바이저 운영 체제와 가상 머신의 리소스를 분리해 VM의 생성과 관리를 지원함
  • 서로 다른 여러 개의 운영 체제를 나란히 구동할 수 있음

 

아직 잘 이해가 안 된다면, Hypervisor라는 이름을 뜯어보자!

In general, operating systems are referred as supervisors.
As a hypervisor software is a supervisor of a “supervisor”, it is called hypervisor.

일반적으로 운영체제를 supervisor라고 부르는데, 하이퍼바이저는 supervisor의 supervisor라고 한다.

 

 

Type 1 vs Type 2

가상화는 크게 Type1와 Type2로 분류된다.

Type1 방식은 Native 혹은 베어메탈(Bare Metal)형 하이퍼바이저 가상화라고도 부른다. 베어메탈이란 하드웨어 상에 어떤 소프트웨어도 설치되어 있지 않은 상태이다. Type1은 베어메탈 하드웨어 위에 직접 설치되어 구동된다. ESX-i(vmware), Xen, KVM, XenServer(citrix), Hyper-V(Microsoft) 등이 있다. 하이퍼바이저는 전가상화와 반가상화로 나뉜다.

 

Type2 방식은 Host 가상화라고 부른다. 베어메탈 하드웨어 위에 Host OS가 설치되고, 그 위에 하이퍼바이저가 실행되는 형태이다. 테스트 환경을 구성할 때 자주 사용하는 Oracle VirtualBox나 VMware Workstation이 여기에 해당된다.

 

Type2 방식 Host OS라는 하나의 레이어가 더 존재하므로, 성능 면에서 Type1이 Type2보다 유리하다. 실제 IDC 클라우드화 시키는데 사용되는 하이퍼바이저도 모두 Type1 방식이다.

 

 

 

 

 

 

참고링크

PostgreSQL에 대한 과제를 진행하기 때문에 장고 프로젝트에 PostgreSQL을 연동하여 사용해고자 한다.

 

먼저, PostgreSQL을 설치하고 DB를 생성해야 한다.

 

맥(Mac)에 PostgreSQL 설치 + DBeaver 연결

PostgreSQL 설치 1. 터미널에서 brew를 이용하여 설치 brew install postgresql 2. 버전 확인 postgres -V 3. 시작 brew services start postgresql 4. 접속 psql postgres 종료 brew services stop postgresql DBeaver 연결 1. DBeaver 다운로

myminju.tistory.com

 

완료되었으면 Django에 psycopg2를 설치해준다.

pip install psycopg2

 

설치가 되었으면 settings.py의 DATABASE 항목에 연결정보를 입력한다.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'project',
        'USER': 'root',
        'PASSWORD': 'password',
        'HOST': 'localhost',
        'PORT': '',
    }
}

 

그 후 터미널에서 아래와 같이 입력하고 서버 구동을 확인한다.

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

 

아래와 같이 장고 프로젝트에 잘 연동되어 데이터가 출력되는 것을 확인할 수 있다!

 

 

 

Reference

https://velog.io/@chaeri93/Django-Django와-Postgresql-연동하기

+ Recent posts