Opensourcetechブログ

OpensourcetechによるNGINX/Kubernetes/Zabbix/Neo4j/Linuxなどオープンソース技術に関するブログです。

Vagrantによる仮想マシン(VM)制御

こんにちは、LinuCエバンジェリストこと、鯨井貴博@opensourcetechです。

 

今回は、Vagrantを使って Virtialbox上に仮想マシンを作成する流れについてまとめます。

※Virtualboxについては、こちらからダウンロードしてインストールしてください。

 

 

 

Vagrantのダウンロード

Vagrantは、HashiCorpが開発している仮想化ソフトウェアを支援するツールです。

Download - Vagrant by HashiCorp

f:id:opensourcetech:20190125021316p:plain

f:id:opensourcetech:20190125021311p:plain

 

ダウンロードしたファイルをクリックし、インストールします。

f:id:opensourcetech:20190125021322p:plain

f:id:opensourcetech:20190125021327p:plain

 

 

 

Vagrantの操作

Vagrantの操作はコマンドラインから実施します。

サブコマンドのboxでイメージファイルの管理、initでVagrantfileと呼ばれる設定情報を作成、upでイメージを使って仮想マシンを作成・起動するなどの使い方が出来ます。

bash-3.2$ vagrant
Usage: vagrant [options] <command> [<args>]

-v, --version Print the version and exit.
-h, --help Print this help.

Common commands:
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`.

 

 

 

 

イメージファイル(box)について

インストール後、「box」と呼ばれる仮想マシンに使用するイメージファイルを、使用したいものをVagrant Cloudから取得します。

Discover Vagrant Boxes - Vagrant Cloud

 

検索ボックスに、使いたいディストリビューション名などを入れると、該当するものが検索されます。

f:id:opensourcetech:20190125021333p:plain

 

f:id:opensourcetech:20190125021338p:plain

 

今回は、box(イメージファイル)をコマンドで取得しました。

bash-3.2$ vagrant box list・・・・ローカルのboxリスト一覧確認
There are no installed boxes! Use `vagrant box add` to add some.
bash-3.2$ vagrant box add centos/7・・・・CentOS7イメージを取得
/opt/vagrant/embedded/gems/2.2.3/gems/vagrant-2.2.3/lib/vagrant/util/which.rb:37: warning: Insecure world writable dir /Applications/Xamarin Workbooks.app/Contents/SharedSupport/path-bin in PATH, mode 040777
==> box: Loading metadata for box 'centos/7'
box: URL: https://vagrantcloud.com/centos/7
This box can work with multiple providers! The providers that it
can work with are listed below. Please review the list and choose
the provider you will be working with.

1) hyperv
2) libvirt
3) virtualbox
4) vmware_desktop

Enter your choice: 3・・・・virtualbox用のイメージを選択
==> box: Adding box 'centos/7' (v1812.01) for provider: virtualbox
box: Downloading: https://vagrantcloud.com/centos/boxes/7/versions/1812.01/providers/virtualbox.box
box: Download redirected to host: cloud.centos.org
==> box: Successfully added box 'centos/7' (v1812.01) for 'virtualbox'!
bash-3.2$ vagrant box list
centos/7 (virtualbox, 1812.01)

 

 

Vagrantfileの作成

 VMの元となる「Vagrantfile」を作成します。

bash-3.2$ mkdir vagrant_centos7・・・・centos7用のVagrantfile格納場所作成

bash-3.2$ cd vagrant_centos7/
bash-3.2$ vagrant init centos/7
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.
bash-3.2$ ls -l
total 8
-rw-r--r-- 1 kujiraitakahiro staff 3015 1 22 23:50 Vagrantfile・・・・作成されたファイル
bash-3.2$ cat Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
# The most common configuration options are documented and commented below.
# For a complete reference, please see the online documentation at
# https://docs.vagrantup.com.

# Every Vagrant development environment requires a box. You can search for
# boxes at https://vagrantcloud.com/search.
config.vm.box = "centos/7"

# Disable automatic box update checking. If you disable this, then
# boxes will only be checked for updates when the user runs
# `vagrant box outdated`. This is not recommended.
# config.vm.box_check_update = false

# Create a forwarded port mapping which allows access to a specific port
# within the machine from a port on the host machine. In the example below,
# accessing "localhost:8080" will access port 80 on the guest machine.
# NOTE: This will enable public access to the opened port
# config.vm.network "forwarded_port", guest: 80, host: 8080

# Create a forwarded port mapping which allows access to a specific port
# within the machine from a port on the host machine and only allow access
# via 127.0.0.1 to disable public access
# config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"

# Create a private network, which allows host-only access to the machine
# using a specific IP.
# config.vm.network "private_network", ip: "192.168.33.10"

# Create a public network, which generally matched to bridged network.
# Bridged networks make the machine appear as another physical device on
# your network.
# config.vm.network "public_network"

# Share an additional folder to the guest VM. The first argument is
# the path on the host to the actual folder. The second argument is
# the path on the guest to mount the folder. And the optional third
# argument is a set of non-required options.
# config.vm.synced_folder "../data", "/vagrant_data"

# Provider-specific configuration so you can fine-tune various
# backing providers for Vagrant. These expose provider-specific options.
# Example for VirtualBox:
#
# config.vm.provider "virtualbox" do |vb|
# # Display the VirtualBox GUI when booting the machine
# vb.gui = true
#
# # Customize the amount of memory on the VM:
# vb.memory = "1024"
# end
#
# View the documentation for the provider you are using for more
# information on available options.

# Enable provisioning with a shell script. Additional provisioners such as
# Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the
# documentation for more information about their specific syntax and use.
# config.vm.provision "shell", inline: <<-SHELL
# apt-get update
# apt-get install -y apache2
# SHELL
end

 

 

VMの作成・起動

 作成済みのVagrantfileを用いて、仮想マシン(VM)を作成・起動します。

bash-3.2$ vagrant status・・・・VM起動前の状態確認
/opt/vagrant/embedded/gems/2.2.3/gems/vagrant-2.2.3/lib/vagrant/util/which.rb:37: warning: Insecure world writable dir /Applications/Xamarin Workbooks.app/Contents/SharedSupport/path-bin in PATH, mode 040777
Current machine states:

default not created (virtualbox)・・・・まだ何もない

The environment has not yet been created. Run `vagrant up` to
create the environment. If a machine is not created, only the
default provider will be shown. So if a provider is not listed,
then the machine is not created for that environment.

bash-3.2$ vagrant up
/opt/vagrant/embedded/gems/2.2.3/gems/vagrant-2.2.3/lib/vagrant/util/which.rb:37: warning: Insecure world writable dir /Applications/Xamarin Workbooks.app/Contents/SharedSupport/path-bin in PATH, mode 040777
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'centos/7'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'centos/7' version '1812.01' is up to date...
==> default: Setting the name of the VM: vagrant_centos7_default_1548168790653_77290
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
default: Adapter 1: nat
==> default: Forwarding ports...
default: 22 (guest) => 2222 (host) (adapter 1)
==> 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:
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: No guest additions were detected on the base box for this VM! Guest
default: additions are required for forwarded ports, shared folders, host only
default: networking, and more. If SSH fails on this machine, please install
default: the guest additions and repackage the box to continue.
default:
default: This is not an error message; everything may continue to work properly,
default: in which case you may ignore this message.
==> default: Rsyncing folder: /Users/kujiraitakahiro/vagrant_centos7/ => /vagrant

bash-3.2$ vagrant status
/opt/vagrant/embedded/gems/2.2.3/gems/vagrant-2.2.3/lib/vagrant/util/which.rb:37: warning: Insecure world writable dir /Applications/Xamarin Workbooks.app/Contents/SharedSupport/path-bin in PATH, mode 040777
Current machine states:

default running (virtualbox)・・・・起動した!

The VM is running. To stop this VM, you can run `vagrant halt` to
shut it down forcefully, or you can run `vagrant suspend` to simply
suspend the virtual machine. In either case, to restart it again,
simply run `vagrant up`.

 

Virtualboxマネージャー上でも以下のように、新規マシンが追加されています。

f:id:opensourcetech:20190125021350p:plain

 

 

 

 

VMへのアクセス

 作成したVMへは、サブコマンドsshでアクセスできます。

仮想マシンではIPアドレスなどが付与され、外部との通信も出来ました。

exitとすれば、VMから抜けることができます。

bash-3.2$ vagrant ssh
/opt/vagrant/embedded/gems/2.2.3/gems/vagrant-2.2.3/lib/vagrant/util/which.rb:37: warning: Insecure world writable dir /Applications/Xamarin Workbooks.app/Contents/SharedSupport/path-bin in PATH, mode 040777
[vagrant@localhost ~]$ ip addr show
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
inet6 ::1/128 scope host
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 52:54:00:f0:e9:5b 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 86292sec preferred_lft 86292sec
inet6 fe80::5054:ff:fef0:e95b/64 scope link
valid_lft forever preferred_lft forever
[vagrant@localhost ~]$ ping 1.1.1.1
PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.
64 bytes from 1.1.1.1: icmp_seq=1 ttl=63 time=23.6 ms
^C
--- 1.1.1.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 23.664/23.664/23.664/0.000 ms
[vagrant@localhost ~]$ cat /etc/centos-release
CentOS Linux release 7.6.1810 (Core)
[vagrant@localhost ~]$ uname -a
Linux localhost.localdomain 3.10.0-957.1.3.el7.x86_64 #1 SMP Thu Nov 29 14:49:43 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

[vagrant@localhost ~]$ exit
logout
Connection to 127.0.0.1 closed.

 

VMへの停止

VMの停止は、サブコマンドhaltを使用します。

bash-3.2$ vagrant halt
/opt/vagrant/embedded/gems/2.2.3/gems/vagrant-2.2.3/lib/vagrant/util/which.rb:37: warning: Insecure world writable dir /Applications/Xamarin Workbooks.app/Contents/SharedSupport/path-bin in PATH, mode 040777
==> default: Attempting graceful shutdown of VM...

bash-3.2$ vagrant status
/opt/vagrant/embedded/gems/2.2.3/gems/vagrant-2.2.3/lib/vagrant/util/which.rb:37: warning: Insecure world writable dir /Applications/Xamarin Workbooks.app/Contents/SharedSupport/path-bin in PATH, mode 040777
Current machine states:

default poweroff (virtualbox)

The VM is powered off. To restart the VM, simply run `vagrant up`

 

Virtualboxマネージャー上でも、停止となっていることが確認できます。

f:id:opensourcetech:20190125021356p:plain

 

 

 

まとめ

このようにVagrantを使ってVirtualbox上などに仮想マシン(VM)を作ることができるメリットとしては、box・Vagrantfileを使用することで同一環境の仮想マシンを再現できるということかと思います。

 

学習環境などではありがちな、「Virtualbox GUI上で仮想CPUやメモリーの設定を間違えた」などはVagrantを使用することで回避できそうです。

 

 

 

 

www.slideshare.net

github.com

www.facebook.com

twitter.com

www.instagram.com

 

 

にほんブログ村 IT技術ブログ Linuxへ
Linux

にほんブログ村 IT技術ブログ オープンソースへ
オープンソース

 

 

Opensourcetech by Takahiro Kujirai