happyso
study with happyso
happyso
전체 방문자
오늘
어제
  • 분류 전체보기 (302)
    • GIT (3)
    • 컴퓨터 기본 개념 (29)
    • 알고리즘 (125)
      • 알고리즘 문제 (115)
      • 알고리즘 개념 (10)
    • Go (2)
    • 클라우드 (54)
      • DevOps (4)
      • Kubernetes(쿠버네티스) (33)
      • AWS (6)
      • CKA (8)
    • 리눅스(Linux) (18)
      • 컨테이너(Container) (8)
    • Front (22)
      • JavaScript (2)
      • React (20)
    • Python (21)
      • Python 웹 크롤링 (11)
      • Django (7)
      • MachineLearning (3)
    • 데이터베이스 (6)
      • MariaDB (2)
      • MongoDB (4)
    • C언어 (5)
    • Trouble Shooting (2)
    • 네트워크 (8)
      • CCNA (5)
    • 보안 (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • kubernetes
  • replace
  • edit
  • Patch
  • 18
  • apply
  • 15

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
happyso

study with happyso

[DevOps] 쉘스크립트 반복문/조건문 & CentOS &  Vagrant사용하여 개발환경 공유
클라우드/DevOps

[DevOps] 쉘스크립트 반복문/조건문 & CentOS & Vagrant사용하여 개발환경 공유

2020. 9. 9. 22:53

쉘 스크립트에서 for 루프 사용 방법

root@server:~# vi sigma.sh

#!/bin/sh


hap=0

for i in 1 2 3 4 5 6 7 8 9 10

do

echo $i

hap=`expr $hap + $i`

done

echo "1부터 10까지의 합은 " $hap

exit 0



1부터 100까지의 합을 구하는 쉘 스크립트를 작성하시오.

root@server:~# vi sigma.sh 

#!/bin/sh


hap=0

#for i in 1 2 3 4 5 6 7 8 9 10

for i in $(seq 1 100)

do

hap=`expr $hap + $i`

done

echo "1부터 100까지의 합은 " $hap

exit 0



root@server:~# vi sigma.sh

#!/bin/sh


hap=0

#for i in 1 2 3 4 5 6 7 8 9 10

#for i in $(seq 1 100)

for i in {1..100}

do

hap=`expr $hap + $i`

done

echo "1부터 100까지의 합은 " $hap

exit 0

 

root@server:~# sh sigma.sh

expr: non-integer argument

1부터 100까지의 합은 

 

root@server:~# bash sigma.sh 

1부터 100까지의 합은  5050



root@server:~# vi sigma.sh 

#!/bin/sh


hap=0

#for i in 1 2 3 4 5 6 7 8 9 10

#for i in $(seq 1 100)

#for i in {1..100}

for (( i = 1 ; i <= 100 ; i ++ ))

do

hap=`expr $hap + $i`

done

echo "1부터 100까지의 합은 " $hap

exit 0

 

root@server:~# sh sigma.sh 

sigma.sh: 7: sigma.sh: Syntax error: Bad for loop variable

 

root@server:~# bash sigma.sh 

1부터 100까지의 합은  5050

 

 

Quiz. 

1부터 10까지 숫자 중 짝수의 합을 구하시오.

 

#!/bin/sh


hap=0

for i in 2 4 6 8 10            ⇐ 짝수만 나열

#for i in $(seq 2 2 10)        ⇐ seq 시작 증가치 끝

#for i in {2..10..2}           ⇐ {시작..끝..증가치}

#for (( i = 2 ; i <= 10 ; i += 2 ))

do

hap=`expr $hap + $i`

done

echo "1부터 10까지의 짝수 합은 " $hap

exit 0



Quiz.

아래와 같은 형식으로 구구단을 출력하시오.

 

2 x 1 = 2

2 x 2 = 4 

    :

2 x 9 = 18

-----------

3 x 2 = 3

    :

------------

     :

9 x 9 = 81

-----------

 

root@server:~# vi gugudan.sh

#!/bin/bash

for i in $(seq 1 9)

do 

for j in {1..9}

do

# echo $i " x " $j " = " `expr $i \* $j`

echo $i  x  $j  =  `expr $i \* $j`

done

echo "--------------"

done

exit 0

 

root@server:~# chmod +x gugudan.sh 

root@server:~# ./gugudan.sh 



Quiz.

아래와 같은 형식으로 구구단을 출력하시오.

 

2 x 1 = 2 3 x 1 = 3 .. 9 x 1 = 9

    :     :                     :

2 x 9 = 18 3 x 9 = 27 .. 9 x 9 = 81

 

Hint.

printf "%s x %s = %s \t" $i $j $k

        ~~~~~~~~~~~~

        형식에 맞춰서 변수 i, j, k 값을 출력

만약, i, j, k 값이 9, 8, 72 이면, 9 x 8 = 72 형태로 출력



#!/bin/bash

for j in $(seq 1 9)

do 

for i in {1..9}

do

printf "%s x %s = %s\t" $i $j `expr $i \* $j`

if [ $i = 9 ]

then

printf "\n"

fi

done

done

exit 0

 

root@server:~# ./gugudan.sh 

1 x 1 = 1 2 x 1 = 2 3 x 1 = 3 4 x 1 = 4 ... 8 x 1 = 8 9 x 1 = 9

1 x 2 = 2 2 x 2 = 4 3 x 2 = 6 4 x 2 = 8 ... 8 x 2 = 16 9 x 2 = 18

1 x 3 = 3 2 x 3 = 6 3 x 3 = 9 4 x 3 = 12 ... 8 x 3 = 24 9 x 3 = 27

1 x 4 = 4 2 x 4 = 8 3 x 4 = 12 4 x 4 = 16 ... 8 x 4 = 32 9 x 4 = 36

1 x 5 = 5 2 x 5 = 10 3 x 5 = 15 4 x 5 = 20 ... 8 x 5 = 40 9 x 5 = 45

1 x 6 = 6 2 x 6 = 12 3 x 6 = 18 4 x 6 = 24 ... 8 x 6 = 48 9 x 6 = 54

1 x 7 = 7 2 x 7 = 14 3 x 7 = 21 4 x 7 = 28 ... 8 x 7 = 56 9 x 7 = 63

1 x 8 = 8 2 x 8 = 16 3 x 8 = 24 4 x 8 = 32 ... 8 x 8 = 64 9 x 8 = 72

1 x 9 = 9 2 x 9 = 18 3 x 9 = 27 4 x 9 = 36 ... 8 x 9 = 72 9 x 9 = 81

 



Quiz.

아래 조건을 만족하는 quiz.sh 프로그램을 작성하시오.

  1. 프로그램에서 임의의 숫자를 생성 (rand 명령어를 이용) ⇐ apt install rand 명령어로 rand 설치

  2. 사용자로부터 숫자를 입력받아서 1)에서 생성한 숫자를 맞추는 프로그램

  3. 만약, 사용자가 입력한 숫자가 1)에서 생성한 숫자와 다르면, 크다, 작다 메시지를 출력

  4. 사용자가 입력한 숫자가 1)에서 생성한 숫자와 일치하면 맞다 메시지를 출력

  5. 단, 사용자가 숫자를 입력하는 회수는 10회로 제한하고, 10회를 초과하는 경우 실패 메시지를 출력

 




#!/bin/bash

rnum=$(rand) ⇐ rand 명령어의 실행 결과를 rnum 변수에 할당

if [ $# -gt 0 ] && [ $1 = "debug" ] ⇐ 쉘 스크립트로 전달된 파라미터의 개수가 1개 이상이고, 

then   첫번째 파라미터의 값이 debug인 경우, 생성한 랜덤 넘버를 출력

echo $rnum

fi

for (( i = 0 ; i < 10 ; i ++ )) ⇐ 10번 반복 (사용자 입력과 값 비교) 

do 

echo "Input number :"

read inum ⇐ 사용자 입력을 처리

if [ $inum -eq $rnum ] ⇐ 값이 일치하는지 비교

then

echo "맞다"

exit 0

elif [ $inum -lt $rnum ] ⇐ 값이 작은 경우

then 

echo "작다"

else ⇐ 값이 큰 경우

echo "크다"

fi

done

echo "실패" ⇐ 10번 반복했는데도 일치하지 않는 경우

exit 0



root@server:~# chmod +x quiz.sh 

root@server:~# ./quiz.sh

root@server:~# ./quiz.sh debug ⇐ 디버깅 목적으로 프로그램을 실행 → 랜덤 넘버를 화면에 제공

 

 

구구단 가로 출력과 퀴즈 2개를 각각 구글 문서에 등록해 주세요. 

등록 주소가 다릅니다. 확인하고 등록해 주세요. 

 

가급적이면 보기 좋게 하나의 쉘에 넣어 주세요. 



root@server:~# vi shift.sh

#!/bin/bash

myfunc() {

str=""

while [ "$1" != "" ]; do

str="$str $1"

shift

done

echo $str

}

 

myfunc AAA BBB CCC DDD EEE FFF GGG

exit 0






크론(cron) 등록 

crontab -l ⇐ 등록된 크론을 확인

crontab -e ⇐ 크론을 등록, 수정 



0  5  *  *  1     tar -zcf   /var/backups/home.tgz   /home/

분 시 일 월 요일 

            0~6 : 일~토 




특정 시간에 특정 디렉터리를 백업

root@server:~# vi backup.sh

root@server:~# cat backup.sh 

#!/bin/bash

set $(date)

fname="backup$1$2$3tar.xz" ⇐ 2020.09.09.tar.xz

tar cfJ /backup/$fname /home

 

root@server:~# mkdir /backup

root@server:~# bash ./backup.sh

tar: Removing leading `/' from member names

root@server:~# ls /backup/

backup2020.09.09.tar.xz

 

크론에 등록

root@server:~# vi /etc/crontab

# /etc/crontab: system-wide crontab

# Unlike any other crontab you don't have to run the `crontab'

# command to install the new version when you edit this file

# and files in /etc/cron.d. These files also have username fields,

# that none of the other crontabs do.

 

SHELL=/bin/sh

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

 

# m h dom mon dow user  command

17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly

25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )

47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )

52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )

 

# 매월 16일 새벽 3시 20분에 백업을 수행

20   03   16   *   *    root    /root/backup.sh

#

 

 

사용하지 않는 가상머신 이미지가 있으면 삭제




프로젝트를 수행할 때 절차, 방법, 도구, 산출물 등을 정의하고 있는 것 

⇒ 방법론(method)

 

https://sasperger.tistory.com/136

⇒ 애자일SW개발101 (PDF 파일)

 

Vagrant로 로컬 개발 환경의 Infrastructure as Code 화 (P58)

 

Vagrant ⇒ 해시코드에서 제공하는 가상 환경 구축 도구

 

VirtualBox 6.1 버전을 사용하기 위해서는 Vagrant 2.2.1 보다 높은 버전을 사용해야 함

 

#1 기존에 실행 중 가상머신을 모두 중지 (poweroff)

#2 Vagrant 설치

https://www.vagrantup.com/ 환경에 맞는 설치 파일을 다운로드 받아서 설치



설치하고 리부팅 후 다시 접속해 주세요. 잠시 쉬고 15시 20분에 다시 시작하겠습니다. 

 

#3 작업 디렉터리를 생성

C:\> mkdir C:\HashiCorp\WorkDir



#4 Vagrantfile 파일을 생성

C:\HashiCorp\WorkDir> vagrant init ⇐ Vagrantfile 템플릿을 생성

A `Vagrantfile` has been placed in this directory. You are now

ready to `vagrant up` your first virtual environment! Please read

the comments in the Vagrantfile as well as documentation on

`vagrantup.com` for more information on using Vagrant.

 

C:\HashiCorp\WorkDir> dir

 C 드라이브의 볼륨에는 이름이 없습니다.

 볼륨 일련 번호: 7681-638B

 

 C:\HashiCorp\WorkDir 디렉터리

 

2020-09-09  오후 03:43    <DIR>          .

2020-09-09  오후 03:43    <DIR>          ..

2020-09-09  오후 03:43    <DIR>          .vagrant

2020-09-09  오후 03:43             3,080 Vagrantfile ⇐ 생성된 것을 확인

               1개 파일               3,080 바이트

               3개 디렉터리  113,129,132,032 바이트 남음



#5 Vagrantfile을 편집

# -*- mode: ruby -*-

# vi: set ft=ruby :


Vagrant.configure("2") do |config|

# config.vm.box = "centos/7"

  config.vm.box = "generic/centos7"

  config.vm.hostname = "demo"

  config.vm.network "private_network", ip: "192.168.33.10"

  config.vm.synced_folder ".", "/home/vagrant/sync", disabled: true

end

 

#6 가상머신을 생성하고 기동

C:\HashiCorp\WorkDir> vagrant up

Bringing machine 'default' up with 'virtualbox' provider...

==> default: Box 'generic/centos7' could not be found. Attempting to find and install...

    default: Box Provider: virtualbox

    default: Box Version: >= 0

==> default: Loading metadata for box 'generic/centos7'

    default: URL: https://vagrantcloud.com/generic/centos7

==> default: Adding box 'generic/centos7' (v3.0.30) for provider: virtualbox

    default: Downloading: https://vagrantcloud.com/generic/boxes/centos7/versions/3.0.30/providers/virtualbox.box

==> default: Box download is resuming from prior download progress

Download redirected to host: vagrantcloud-files-production.s3.amazonaws.com

    default:

    default: Calculating and comparing box checksum...

==> default: Successfully added box 'generic/centos7' (v3.0.30) for 'virtualbox'!

==> default: Importing base box 'generic/centos7'...

==> default: Matching MAC address for NAT networking...

==> default: Checking if box 'generic/centos7' version '3.0.30' is up to date...

==> default: Setting the name of the VM: WorkDir_default_1599636778803_68703

==> default: Clearing any previously set network interfaces...

==> default: Preparing network interfaces based on configuration...

    default: Adapter 1: nat

    default: Adapter 2: hostonly

==> default: Forwarding ports...

    default: 22 (guest) => 2222 (host) (adapter 1)

==> default: Running 'pre-boot' VM customizations...

==> default: Booting VM...

==> default: Waiting for machine to boot. This may take a few minutes...

    default: SSH address: 127.0.0.1:2222

    default: SSH username: vagrant

    default: SSH auth method: private key

    default: Warning: Connection aborted. Retrying...

    default: Warning: Connection reset. Retrying...

    default: Warning: Connection aborted. Retrying...

    default: Warning: Connection reset. Retrying...

    default: Warning: Connection aborted. Retrying...

    default:

    default: Vagrant insecure key detected. Vagrant will automatically replace

    default: this with a newly generated keypair for better security.

    default:

    default: Inserting generated public key within guest...

    default: Removing insecure key from the guest if it's present...

    default: Key inserted! Disconnecting and reconnecting using new SSH key...

==> default: Machine booted and ready!

==> default: Checking for guest additions in VM...

    default: The guest additions on this VM do not match the installed version of

    default: VirtualBox! In most cases this is fine, but in rare cases it can

    default: prevent things such as shared folders from working properly. If you see

    default: shared folder errors, please make sure the guest additions within the

    default: virtual machine match the version of VirtualBox you have installed on

    default: your host and reload your VM.

    default:

    default: Guest Additions Version: 5.2.44

    default: VirtualBox Version: 6.1

==> default: Setting hostname...

==> default: Configuring and enabling network interfaces...

 

C:\HashiCorp\WorkDir>

 

 

Encoding::CompatibilityError: incompatible character encodings: UTF-8 and CP-949 오류가 발생하는 경우

 

원인 → 윈도우 사용자 계정명에 한글이 포함된 경우

조치 

  1. 사용자 홈 디렉터리(C:\Users\사용자명) 아래에 있는 .vagrant.d 폴더를 한글이 없는 디렉터리(예: C:\HashCorp)로 복사

  2. 경로 환경 변수에 VAGRANT_HOME 변수를 추가하고 1)에서 설정한 경로를 지정

 

  1. 새로운 명령어 창을 실행해야 변경된 정보가 반영

 



#7 vagrant up 을 통해서 생성한 가상 머신으로 접속

#7-1 방법1. VirtualBox를 이용

 

계정 : vagrant / vagrant 



#7-2 방법2. vagrant ssh 이용 ⇒ 별도의 프로그램 설치나 인증이 필요

C:\HashiCorp\WorkDir> vagrant ssh

Last login: Wed Sep  9 07:52:28 2020

[vagrant@demo ~]$ ip a

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000

    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00

    inet 127.0.0.1/8 scope host lo

       valid_lft forever preferred_lft forever

2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000

    link/ether 08:00:27:52:0f:fe brd ff:ff:ff:ff:ff:ff

    inet 10.0.2.15/24 brd 10.0.2.255 scope global noprefixroute dynamic eth0

       valid_lft 85216sec preferred_lft 85216sec

3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000

    link/ether 08:00:27:32:e4:d4 brd ff:ff:ff:ff:ff:ff

    inet 192.168.33.10/24 brd 192.168.33.255 scope global noprefixroute eth1

       valid_lft forever preferred_lft forever

    inet6 fe80::a00:27ff:fe32:e4d4/64 scope link

       valid_lft forever preferred_lft forever

[vagrant@demo ~]$



#7-3 방법3. SSH 클라이언트를 이용한 접속



키 파일이 있는 위치는 아래 명령어로 확인이 가능

C:\HashiCorp\WorkDir> vagrant ssh-config

Host default

  HostName 127.0.0.1

  User vagrant

  Port 2222

  UserKnownHostsFile /dev/null

  StrictHostKeyChecking no

  PasswordAuthentication no

  IdentityFile C:/HashiCorp/WorkDir/.vagrant/machines/default/virtualbox/private_key

  IdentitiesOnly yes

  LogLevel FATAL

 



[vagrant@demo ~]$ ip a

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000

    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00

    inet 127.0.0.1/8 scope host lo

       valid_lft forever preferred_lft forever

2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000

    link/ether 08:00:27:52:0f:fe brd ff:ff:ff:ff:ff:ff

    inet 10.0.2.15/24 brd 10.0.2.255 scope global noprefixroute dynamic eth0

       valid_lft 84286sec preferred_lft 84286sec

3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000

    link/ether 08:00:27:32:e4:d4 brd ff:ff:ff:ff:ff:ff

    inet 192.168.33.10/24 brd 192.168.33.255 scope global noprefixroute eth1

       valid_lft forever preferred_lft forever

    inet6 fe80::a00:27ff:fe32:e4d4/64 scope link

       valid_lft forever preferred_lft forever

[vagrant@demo ~]$ whoami

vagrant

[vagrant@demo ~]$ uname -n

demo



#8 도움말을 참조해서 스냅샷 생성

C:\HashiCorp\WorkDir> vagrant --help

Usage: vagrant [options] <command> [<args>]

 

    -h, --help                       Print this help.

 

Common commands:

     autocomplete    manages autocomplete installation on host

     box             manages boxes: installation, removal, etc.

     cloud           manages everything related to Vagrant Cloud

     destroy         stops and deletes all traces of the vagrant machine

     global-status   outputs status Vagrant environments for this user

     halt            stops the vagrant machine

     help            shows the help for a subcommand

     init            initializes a new Vagrant environment by creating a Vagrantfile

     login

     package         packages a running vagrant environment into a box

     plugin          manages plugins: install, uninstall, update, etc.

     port            displays information about guest port mappings

     powershell      connects to machine via powershell remoting

     provision       provisions the vagrant machine

     push            deploys code in this environment to a configured destination

     rdp             connects to machine via RDP

     reload          restarts vagrant machine, loads new Vagrantfile configuration

     resume          resume a suspended vagrant machine

     snapshot        manages snapshots: saving, restoring, etc.

     ssh             connects to machine via SSH

     ssh-config      outputs OpenSSH valid configuration to connect to the machine

     status          outputs status of the vagrant machine

     suspend         suspends the machine

     up              starts and provisions the vagrant environment

     upload          upload to machine via communicator

     validate        validates the Vagrantfile

     version         prints current and latest Vagrant version

     winrm           executes commands on a machine via WinRM

     winrm-config    outputs WinRM configuration to connect to the machine

 

For help on any individual command run `vagrant COMMAND -h`

 

Additional subcommands are available, but are either more advanced

or not commonly used. To see all subcommands, run the command

`vagrant list-commands`.

        --[no-]color                 Enable or disable color output

        --machine-readable           Enable machine readable output

    -v, --version                    Display Vagrant version

        --debug                      Enable debug output

        --timestamp                  Enable timestamps on log output

        --debug-timestamp            Enable debug output with timestamps

        --no-tty                     Enable non-interactive output



C:\HashiCorp\WorkDir> vagrant snapshot --help

Usage: vagrant snapshot <subcommand> [<args>]

 

Available subcommands:

     delete

     list

     pop

     push

     restore

     save

 

For help on any individual subcommand run `vagrant snapshot <subcommand> -h`

        --[no-]color                 Enable or disable color output

        --machine-readable           Enable machine readable output

    -v, --version                    Display Vagrant version

        --debug                      Enable debug output

        --timestamp                  Enable timestamps on log output

        --debug-timestamp            Enable debug output with timestamps

        --no-tty                     Enable non-interactive output



C:\HashiCorp\WorkDir> vagrant snapshot save -h

Usage: vagrant snapshot save [options] [vm-name] <name>

 

Take a snapshot of the current state of the machine. The snapshot

can be restored via `vagrant snapshot restore` at any point in the

future to get back to this exact machine state.

 

If no vm-name is given, Vagrant will take a snapshot of

the entire environment with the same snapshot name.

 

Snapshots are useful for experimenting in a machine and being able

to rollback quickly.

    -f, --force                      Replace snapshot without confirmation

        --[no-]color                 Enable or disable color output

        --machine-readable           Enable machine readable output

    -v, --version                    Display Vagrant version

        --debug                      Enable debug output

        --timestamp                  Enable timestamps on log output

        --debug-timestamp            Enable debug output with timestamps

        --no-tty                     Enable non-interactive output

    -h, --help                       Print this help



C:\HashiCorp\WorkDir> vagrant snapshot save FirstSnapshot

==> default: Snapshotting the machine as 'FirstSnapshot'...

==> default: Snapshot saved! You can restore the snapshot at any time by

==> default: using `vagrant snapshot restore`. You can delete it using

==> default: `vagrant snapshot delete`.

 



#9 가상 머신을 정지 및 삭제

C:\HashiCorp\WorkDir> vagrant halt

==> default: Attempting graceful shutdown of VM...

 

C:\HashiCorp\WorkDir> vagrant destroy

    default: Are you sure you want to destroy the 'default' VM? [y/N] y

==> default: Destroying VM and associated drives...




Vagrant를 이용해서 팀 전체가 웹 서버가 설치된 동일한 가상 머신 환경을 공유 (P66)

https://www.vagrantup.com/docs/provisioning


#1 Vagrantfile에 provisioning 내용을 추가

C:\HashiCorp\WorkDir\Vagrantfile

# -*- mode: ruby -*-

# vi: set ft=ruby :


Vagrant.configure("2") do |config|

# config.vm.box = "centos/7"

  config.vm.box = "generic/centos7"

  config.vm.hostname = "demo"

  config.vm.network "private_network", ip: "192.168.33.10"

  config.vm.synced_folder ".", "/home/vagrant/sync", disabled: true

  config.vm.provision "shell", inline: $script

end


$script = <<SCRIPT

  yum install -y epel-release

  yum install -y nginx

  echo "Hello, Vagrant" > /usr/share/nginx/html/index.html

  systemctl start nginx

SCRIPT

 

#2 provisioning 실행

C:\HashiCorp\WorkDir> vagrant up

Bringing machine 'default' up with 'virtualbox' provider...

==> default: Importing base box 'generic/centos7'...

==> default: Matching MAC address for NAT networking...

==> default: Checking if box 'generic/centos7' version '3.0.30' is up to date...

==> default: Setting the name of the VM: WorkDir_default_1599640437410_82346

==> default: Clearing any previously set network interfaces...

==> default: Preparing network interfaces based on configuration...

    default: Adapter 1: nat

    default: Adapter 2: hostonly

==> default: Forwarding ports...

    default: 22 (guest) => 2222 (host) (adapter 1)

==> default: Running 'pre-boot' VM customizations...

==> default: Booting VM...

:

==> default: Setting hostname...

==> default: Configuring and enabling network interfaces...

==> default: Running provisioner: shell...

    default: Running: inline script

    default: Loaded plugins: fastestmirror

    default: Determining fastest mirrors

    default:  * base: mirror.kakao.com

    default:  * epel: ftp.jaist.ac.jp

    default:  * extras: mirror.kakao.com

    default:  * updates: mirror.kakao.com

    default: Package epel-release-7-12.noarch already installed and latest version

    default: Nothing to do

    default: Loaded plugins: fastestmirror

    default: Loading mirror speeds from cached hostfile

    default:  * base: mirror.kakao.com

    default:  * epel: ftp.jaist.ac.jp

    default:  * extras: mirror.kakao.com

    default:  * updates: mirror.kakao.com

     :

 

C:\HashiCorp\WorkDir>

 

#3 결과를 확인

C:\HashiCorp\WorkDir> vagrant ssh ⇐ 호스트 PC에서 가신머신으로 SSH로 접속

[vagrant@demo ~]$ cat /usr/share/nginx/html/index.html ⇐ nginx 설치 여부 및 index.html 파일 수정 여부를 확인

Hello, Vagrant

[vagrant@demo ~]$ sudo systemctl stop firewalld ⇐ 방화벽 해제

 

[vagrant@demo ~]$ exit ⇐ 가상머신에 빠져 나옴

logout

Connection to 127.0.0.1 closed.

 

C:\HashiCorp\WorkDir> curl http://192.168.33.10 ⇐ 가상머신(nginx서버)에게 웹 페이지(index.html)를 요청

Hello, Vagrant ⇐ index.html 파일의 내용을 반환



curl은(는) 내부 또는 외부 명령, 실행할 수 있는 프로그램, 또는 배치 파일이 아닙니다 오류가 발생하는 경우

⇒ 호스트 PC의 브라우저에서 주소창에 http://192.168.33.10 으로 접속했을 때 Hello, Vagrant가 출력되는지 확인

 

가상 머신이 기동된 후에 provison에 기술된 내용을 실행할 경우 

> vagrant provision 

또는

> vagrant reload --provision




교재 59페이지 ~ 68페이지 내용과 함께 복습해 보세요. 



'클라우드 > DevOps' 카테고리의 다른 글

[LitmusChaos] Developer Guide  (0) 2025.05.25
[DevOps] Docker & Docker Compose & Jenkins(Ansible/Serverspec실행, PipeLine, Parameter)  (0) 2020.09.12
[DevOps] 가상머신 이미지 파일 가져오기 & 앤서블(Ansible) & 인프라 테스트 자동화(Serverspec) & 테스트 결과 HTML 형식으로 출력  (0) 2020.09.10
    '클라우드/DevOps' 카테고리의 다른 글
    • [LitmusChaos] Developer Guide
    • [DevOps] Docker & Docker Compose & Jenkins(Ansible/Serverspec실행, PipeLine, Parameter)
    • [DevOps] 가상머신 이미지 파일 가져오기 & 앤서블(Ansible) & 인프라 테스트 자동화(Serverspec) & 테스트 결과 HTML 형식으로 출력
    happyso
    happyso

    티스토리툴바