7
6

More than 5 years have passed since last update.

Vagrantを使ったVirtualBoxへのVM構築

Last updated at Posted at 2019-04-06

今更感あるけど、VirtualBoxは使ってるけどVMをいちいち作ったり整備するのが(Docker触ってしまうと特に)めんどうだなーと思ってて、でもそういえば Vagrant というものを使えばそのあたり便利になるらしいと聞いて。

環境

  • ホストOS: Windows 10 Home (x64)
  • ハイパーバイザ: VirtualBox 5.2.26
  • Vagrant: v2.2.4

ここではVagrantのみ。VirtualBoxはインストール済みとする。

参考サイト

Vagrantのインストール

ホストOSがWindows10(x64)なので、Windows用64bit版をダウンロード。
2019.04.06時点でv2.2.4を入手可能

ダウンロードできたらインストーラを起動。

image.png

特に調整は必要なく淡々と進めるとインストールは完了するはず。
インストールが完了するとOS再起動を要求される。
起動後は、インストールしたディレクトリ直下のbinにPATHが追加されており、vagrantコマンドが使えるようになる。

PS C:\Users\zaki> vagrant --version
Vagrant 2.2.4
PS C:\Users\zaki> vagrant --help
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`.
PS C:\Users\zaki>

Boxの検索

元となるBoxを検索する。
BoxとはVagrant用のOSイメージのテンプレートらしい。
コンテナ環境でいうコンテナイメージに相当するのかな。

とりあえずCentOSで検索してヒットしたこちらのBoxを使ってみよう
https://app.vagrantup.com/centos/boxes/7

Vagrantfileの作成

Dockerfileに相当

Vagrantfileのテンプレートは検索ページに掲載されているが、コメントやオプションがばっさり削られているので、コマンドを実行して作成する。

image.png

検索して出てきたコマンドを実行する。
カレントディレクトリにファイルが作成されるのでワーク用のディレクトリで実行するとよい。

PS C:\Users\zaki\src\vagrant> 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.

これで実行したディレクトリにVagrantfileが生成される。

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(CentOS)の作成と起動

起動するにはvagrant upコマンドを使用

PS C:\Users\zaki\src\vagrant> vagrant up --help
Usage: vagrant up [options] [name|id]

Options:

        --[no-]provision             Enable or disable provisioning
        --provision-with x,y,z       Enable only certain provisioners, by type or by name.
        --[no-]destroy-on-error      Destroy machine if any fatal error happens (default to true)
        --[no-]parallel              Enable or disable parallelism if provider supports it
        --provider PROVIDER          Back the machine with a specific provider
        --[no-]install-provider      If possible, install the provider if it isn't installed
    -h, --help                       Print this help
PS C:\Users\zaki\src\vagrant>

実行すると、初回(Boxファイル実体がない場合)はダウンロードから始まる。初めてのイメージをdocker runしたときと同じですね。

PS C:\Users\zaki\src\vagrant> vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Box 'centos/7' could not be found. Attempting to find and install...
    default: Box Provider: virtualbox
    default: Box Version: >= 0
==> default: Loading metadata for box 'centos/7'
    default: URL: https://vagrantcloud.com/centos/7
==> default: Adding box 'centos/7' (v1902.01) for provider: virtualbox
    default: Downloading: https://vagrantcloud.com/centos/boxes/7/versions/1902.01/providers/virtualbox.box
    default: Download redirected to host: cloud.centos.org
    default:
==> default: Successfully added box 'centos/7' (v1902.01) for 'virtualbox'!
==> default: Importing base box 'centos/7'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'centos/7' version '1902.01' is up to date...
==> default: Setting the name of the VM: vagrant_default_1554529542430_97950
==> 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: /cygdrive/c/Users/zaki/src/vagrant/ => /vagrant
PS C:\Users\zaki\src\vagrant>

作成が終わるとVirtualBoxのVMマネージャはこんな感じで、ヘッドレス起動でちゃんとVMが稼働している。

image.png

なるほど、OSのインストールは簡単だ。

素のVMの状態

sshログイン

IPアドレスの指定をしてなかったのでsshどうするんだろうと思ったけど、vagrant sshを実行すると稼働しているVMにログインできる。
minikube sshとかと同じ要領だな。

PS C:\Users\zaki\src\vagrant> vagrant ssh
[vagrant@localhost ~]$ hostname
localhost.localdomain
[vagrant@localhost ~]$
[vagrant@localhost ~]$ cat /etc/centos-release
CentOS Linux release 7.6.1810 (Core)
[vagrant@localhost ~]$
[vagrant@localhost ~]$ uname -a
Linux localhost.localdomain 3.10.0-957.5.1.el7.x86_64 #1 SMP Fri Feb 1 14:54:57 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
[vagrant@localhost ~]$ df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        40G  2.8G   38G   7% /
devtmpfs        236M     0  236M   0% /dev
tmpfs           244M     0  244M   0% /dev/shm
tmpfs           244M  4.5M  240M   2% /run
tmpfs           244M     0  244M   0% /sys/fs/cgroup
tmpfs            49M     0   49M   0% /run/user/0
tmpfs            49M     0   49M   0% /run/user/1000
[vagrant@localhost ~]$ free -h
              total        used        free      shared  buff/cache   available
Mem:           487M         57M        301M        4.5M        128M        391M
Swap:          2.0G          0B        2.0G

スペック値的にも起動中のVMであっているようだ。

ネットワーク

VirtualBoxのVMマネージャで見るとデフォルトのNATが1個くっついてるのでインターネットアクセス用のDHCPが1個かな

[vagrant@localhost ~]$ 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
    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:26:10:60 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 84696sec preferred_lft 84696sec
    inet6 fe80::5054:ff:fe26:1060/64 scope link
       valid_lft forever preferred_lft forever
[vagrant@localhost ~]$

その通りだった。

フィルタは特になし

[root@localhost ~]# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
[root@localhost ~]#

yum update

NATでインターネットにはアクセスできるはずなので試してみる。

[vagrant@localhost ~]$ sudo su -
[root@localhost ~]#
[root@localhost ~]#
[root@localhost ~]#
[root@localhost ~]# yum update
Loaded plugins: fastestmirror
Determining fastest mirrors
 * base: ftp.iij.ad.jp
 * extras: ftp.iij.ad.jp
 * updates: ftp.iij.ad.jp
base                                                                                             | 3.6 kB  00:00:00
extras                                                                                           | 3.4 kB  00:00:00
updates                                                                                          | 3.4 kB  00:00:00
(1/4): base/7/x86_64/group_gz                                                                    | 166 kB  00:00:00
(2/4): extras/7/x86_64/primary_db                                                                | 187 kB  00:00:00
(3/4): updates/7/x86_64/primary_db                                                               | 3.4 MB  00:00:01
(4/4): base/7/x86_64/primary_db                                                                  | 6.0 MB  00:00:01
Resolving Dependencies
--> Running transaction check
---> Package NetworkManager.x86_64 1:1.12.0-8.el7_6 will be updated
---> Package NetworkManager.x86_64 1:1.12.0-10.el7_6 will be an update
:
:
--> Finished Dependency Resolution

Dependencies Resolved

========================================================================================================================
 Package                            Arch                 Version                            Repository             Size
========================================================================================================================
Installing:
 kernel                             x86_64               3.10.0-957.10.1.el7                updates                48 M
Updating:
 NetworkManager                     x86_64               1:1.12.0-10.el7_6                  updates               1.7 M
 NetworkManager-libnm               x86_64               1:1.12.0-10.el7_6                  updates               1.4 M
 NetworkManager-team                x86_64               1:1.12.0-10.el7_6                  updates               159 k
 NetworkManager-tui                 x86_64               1:1.12.0-10.el7_6                  updates               239 k
 dbus                               x86_64               1:1.10.24-13.el7_6                 updates               245 k
 dbus-libs                          x86_64               1:1.10.24-13.el7_6                 updates               169 k
 kernel-tools                       x86_64               3.10.0-957.10.1.el7                updates               7.1 M
 kernel-tools-libs                  x86_64               3.10.0-957.10.1.el7                updates               7.0 M
 libblkid                           x86_64               2.23.2-59.el7_6.1                  updates               181 k
 libgcc                             x86_64               4.8.5-36.el7_6.1                   updates               102 k
 libgomp                            x86_64               4.8.5-36.el7_6.1                   updates               157 k
 libmount                           x86_64               2.23.2-59.el7_6.1                  updates               182 k
 libsmartcols                       x86_64               2.23.2-59.el7_6.1                  updates               140 k
 libssh2                            x86_64               1.4.3-12.el7_6.2                   updates               135 k
 libstdc++                          x86_64               4.8.5-36.el7_6.1                   updates               305 k
 libuuid                            x86_64               2.23.2-59.el7_6.1                  updates                82 k
 nss-pem                            x86_64               1.0.3-5.el7_6.1                    updates                74 k
 openssl                            x86_64               1:1.0.2k-16.el7_6.1                updates               493 k
 openssl-libs                       x86_64               1:1.0.2k-16.el7_6.1                updates               1.2 M
 polkit                             x86_64               0.112-18.el7_6.1                   updates               168 k
 python-perf                        x86_64               3.10.0-957.10.1.el7                updates               7.1 M
 shadow-utils                       x86_64               2:4.1.5.1-25.el7_6.1               updates               1.1 M
 tuned                              noarch               2.10.0-6.el7_6.3                   updates               254 k
 tzdata                             noarch               2019a-1.el7                        updates               494 k
 util-linux                         x86_64               2.23.2-59.el7_6.1                  updates               2.0 M
 xfsprogs                           x86_64               4.5.0-19.el7_6                     updates               897 k

Transaction Summary
========================================================================================================================
Install   1 Package
Upgrade  26 Packages

Total download size: 81 M
Is this ok [y/d/N]:

ちゃんと動いてるな

vagrantコマンド

Box一覧

PS C:\Users\zaki\src\vagrant> vagrant box list
centos/7 (virtualbox, 1902.01)
PS C:\Users\zaki\src\vagrant>

VM一覧でなく(ダウンロードして登録済みの)Box一覧だと思う。
たぶんdocker imagesに相当してる感覚。

VMの停止

通常はVMの中でshutdownとかすればいいと思うけど、vagrant側から停止したい場合

PS C:\Users\zaki\src\vagrant> vagrant halt
==> default: Attempting graceful shutdown of VM...
PS C:\Users\zaki\src\vagrant>

VirtualBoxのマネージャで見ても停止した

VM削除

作り直したいとかでVMを削除する場合。

PS C:\Users\zaki\src\vagrant> vagrant destroy
    default: Are you sure you want to destroy the 'default' VM? [y/N] y
==> default: Destroying VM and associated drives...
PS C:\Users\zaki\src\vagrant>

VirtualBoxのマネージャからも消え、エクスプローラ上のVMの実ファイルも消去した。
※ VMがシャットダウンされてなくても実行可能

Boxが消えるわけではないので、Dockerでいえばデプロイ済みのコンテナが削除されイメージは残る感じ

VMの設定(Vagrantfile)

いくつかの設定方法について

VirtualBox上のマシン名

無指定だとやたら長いランダムなVM名になってしまうので、これを任意の名前に設定したい

image.png

Vagrantfileの、プロバイダの設定部分でnameに指定する。
前述のCentOSのVagrantfileであれば、以下の通り。
(vb.nameという設定項目はなかったので新しく追加する。vbの部分はconfig.vm.providerの行の末尾の|vb|のもの)

Vagrantfile
  # 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"

    # VM name
    vb.name = "vagrant vm"
  end

これでVMを作成(vagrant up)すると

image.png

できた。

IPアドレス

デフォルトではNATのNICしか設定されてないため、インターネットには接続できるがホストOSから接続できない。

ホストOSからの通信経路を作成するには、ホストオンリーアダプタのNICを追加する。
Ubuntu 18.04(on VirtualBox) ホストOSからの通信 - Qiita

ホストオンリーアダプタのNICを追加・IPアドレスを指定するには、以下の設定を追加する(vagrant initでテンプレートができているはず)

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

NICが二つになった

image.png

VMのネットワーク状態

PS C:\Users\zaki\src\vagrant> vagrant ssh
[vagrant@localhost ~]$
[vagrant@localhost ~]$
[vagrant@localhost ~]$
[vagrant@localhost ~]$ 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
    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:26:10:60 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 86195sec preferred_lft 86195sec
    inet6 fe80::5054:ff:fe26:1060/64 scope link
       valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 08:00:27:8c:bc:c5 brd ff:ff:ff:ff:ff:ff
    inet 192.168.244.200/24 brd 192.168.244.255 scope global noprefixroute eth1
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fe8c:bcc5/64 scope link
       valid_lft forever preferred_lft forever

ホストOSからの通信

zaki@mascarpone% ping 192.168.244.200
192.168.244.200 に ping を送信しています 32 バイトのデータ:
192.168.244.200 からの応答: バイト数 =32 時間 <1ms TTL=64
192.168.244.200 からの応答: バイト数 =32 時間 <1ms TTL=64
192.168.244.200 からの応答: バイト数 =32 時間 <1ms TTL=64
192.168.244.200 からの応答: バイト数 =32 時間 <1ms TTL=64

192.168.244.200 の ping 統計:
    パケット数: 送信 = 4、受信 = 4、損失 = 0 (0% の損失)、
ラウンド トリップの概算時間 (ミリ秒):
    最小 = 0ms、最大 = 0ms、平均 = 0ms
zaki@mascarpone% 
zaki@mascarpone% ssh vagrant@192.168.244.200
The authenticity of host '192.168.244.200 (192.168.244.200)' can't be established.
ECDSA key fingerprint is SHA256:ROyn7SwPQ9EQ1MGRvBi7e83A0neN0uncKCOlaSq9DhU.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.244.200' (ECDSA) to the list of known hosts.vagrant@192.168.244.200: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).
zaki@mascarpone% 

おっと、パスワード認証が許可されてなかった。

[root@localhost ~]# grep -i passwordauthentication /etc/ssh/sshd_config
#PasswordAuthentication yes
PasswordAuthentication no
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication, then enable this but set PasswordAuthentication
[root@localhost ~]#

↑をyesにしてsystemctl restart sshdすれば

zaki@mascarpone% ssh vagrant@192.168.244.200
vagrant@192.168.244.200's password: 
Last login: Sat Apr  6 07:31:01 2019 from 10.0.2.2
[vagrant@localhost ~]$ 

入れた

hostname設定

hostnameコマンドを実行した場合のホスト名を設定するには、以下追加。

Vagrantfile
  # OS hostname
  config.vm.hostname = "vagrant-01.sample"
[vagrant@vagrant-01 ~]$ hostname
vagrant-01.sample
[vagrant@vagrant-01 ~]$ hostname -s
vagrant-01
[vagrant@vagrant-01 ~]$

できました。


マシン名・ホスト名・IPアドレスの設定をまとめると、以下の通り

Vagrantfile
Vagrant.configure("2") do |config|
  config.vm.box = "centos/7"
  config.vm.network "private_network", ip: "192.168.244.200"
  config.vm.hostname = "vagrant-01.sample"

  config.vm.provider "virtualbox" do |vb|
    vb.name = "vagrant vm"
  end
end

これで「Dockerに比べるとVM作るのめんどくせ~~」というのがちょっと緩和されるかな?
というよりは、IaCによって再構築が格段に楽になりそう。

残件

マシンスペック(CPU・メモリ・ストレージ)などの設定がまだ
2019.09.14: 別記事に書きました。
Vagrantで作成するVMのスペック等の設定(cpu/memory/storageほか) - Qiita

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6