Vagrant オレ的備忘録

# イントロ
VirtualboxのGUIでポチポチ設定していくのが億劫になったのでVagrantでやろうと思った時に色んな記事見るのすら億劫になったのでこの記事を作成した次第。
現時点で自分がわかっていることをつらつら書いていきます。
Docker使えよと言われたらグーの音も出ないので心にしまっておいて下さい。



# コマンド一覧
| コマンド                     |使用例               |コメント                      |
|:--------------------------|:-------------------|:--------------------------|
|vagrant box add [image名 or URL]  |vagrant box add centos/7|OSイメージみたいなもん。決まった書き方かURL指定で作成可能|
|vagrant init [box名]|vagrant init centos/7|box名を入れない場合はVagrantfileのconfig.vm.boxを後で設定する必要あり|
|vagrant up|vagrant up|VMの起動|
|vagrant reload|vagrant reload|VMの再起動|
|vagrant halt|vagrant halt|VMの停止|
|vagrant ssh|vagrant ssh|VMへSSH接続|
|vagrant status|vagrant status|Vagrantfileがあるディレクトリで実行すると、VMの実行状態が分かる|
|vagrant global-status|vagrant global-status|VMの一覧が見れる|
|vagrant destroy [id]| vagrant destroy 72458cf|vagrant global-status を実行時に出力されるIDを指定|

# VM起動までの流れ
## 環境(2020/08/01 時点)
- MacBookPro 13inch 2020モデル
- Vertualbox Ver.6.1（install済み前提）
- Vagrant 2.2.9（install済み前提）

## box の作成と確認
```bash
$ vagrant box add centos/7
==> 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 # 今回VirrtualBoxを使用するので3を選択
==> box: Adding box 'centos/7' (v2004.01) for provider: virtualbox
    box: Downloading: https://vagrantcloud.com/centos/boxes/7/versions/2004.01/providers/virtualbox.box
Download redirected to host: cloud.centos.org
    box: Calculating and comparing box checksum...
==> box: Successfully added box 'centos/7' (v2004.01) for 'virtualbox'!

$ vagrant box list
centos/7 (virtualbox, 2004.01)
```

## VM実行ディレクトリの作成とVagrantfile作成
```bash
$ mkdir centos7
$
$ cd centos7
$
$ ls
$
$ 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.
$
$ ls
Vagrantfile
$
＄ vagrant status
Current machine states:

default                   not created (virtualbox) # VagrantfileはあるがVMはまだ作成されていない状態

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.
$
```

## VM起動とVMへの接続
```bash
$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'centos/7'...
・
・
・
    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/souta/work/vagrant/centos7/ => /vagrant
＄
$ vagrant status
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`.
$
$ vagrant ssh
[vagrant@localhost ~]$
```
この段階でVirtualboxの方を確認すると、作成されているのが分かる。

<img width="952" alt="スクリーンショット 2020-08-01 13.15.27.png" src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/373211/098605fe-eb98-97f1-7a4a-16c27a3bd8aa.png">

## VMの停止
```bash
$ vagrant halt
==> default: Attempting graceful shutdown of VM...
$
```
Virtualboxを確認すると停止しているのが分かる。
<img width="952" alt="スクリーンショット 2020-08-01 13.20.18.png" src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/373211/d8a57022-ca66-f122-9c64-67c3cd19c200.png">

これで起動までは出来た。
次にVagrantfileの設定を見てみる。

# Vagrantfile の設定

## 初期状態のVagrantfileを確認

```bash: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" # initした時に指定したbox名が明記されている

  # 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
  # Ansible, Chef, Docker, Puppet and Salt 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
```

### 基本的に設定変更するであろう項目一覧
以下の設定は``config.vm.provider "virtualbox" do |vb|`` 〜 ``end`` で挟んで指定する。
変更後のVagrantfileを確認してもらえればわかると思う。

| 設定項目                     |意味               |
|:--------------------------|:-------------------|
|vb.memory|メモリ　デフォルトは500MB（単位はMB）|
|vb.cpus|CPU数　デフォルトは1|
|vb.name|VM名|
|vb.gui|GUIの有無　基本はfalseでいいと思う。デフォルトはfalse|


### 共有ディレクトリの設定

- Vagrantfile内の設定項目の修正

設定項目は以下。カレントディレクトリはVagrantfileが配置されているディレクトリとなる。

```bash:Vagrantfile
config.vm.synced_folder "host側の任意のディレクトリ名" "VM内のディレクトリ名"
# 例
config.vm.synced_folder "./data" "/home/vagrant/vagrant_data"
```

- host側の共有ディレクトリの作成

VM側は起動時に自動的に作成される為、気にしなくて良い。

```bash
$ mkdir ./data
```

- 共有するのに必要なプラグインのインストール

```bash
$ vagrant plugin install vagrant-vbguest
```

- VMの起動または再起動

```bash
$ vagrant up
or
$ vagrant reload
```

- 共有の確認

host側のカレントディレクトリはVagrantfileが配置されているディレクトリ。

```bash
$ vagrant ssh
Last login: Fri Jul 31 18:40:40 2020 from 10.0.2.2
[vagrant@localhost ~]$ 
[vagrant@localhost ~]$ ls -lrt
total 0
drwxr-xr-x. 1 vagrant vagrant 96 Aug  1 05:13 vagrant_data
[vagrant@localhost ~]$ cd vagrant_data/
[vagrant@localhost vagrant_data]$ pwd
/home/vagrant/vagrant_data
[vagrant@localhost vagrant_data]$ touch test.txt
[vagrant@localhost vagrant_data]$ ls -lrt
total 0
-rw-r--r--. 1 vagrant vagrant 0 Aug  1 05:13 test.txt
[vagrant@localhost ~]$ exit
logout
Connection to 127.0.0.1 closed.
$
$ cd data
$ ls -lrt
total 0
-rw-r--r--  1 user  group  0  8  1 14:13 test.txt
$
```

VM内のタイムスタンプがバグってるが、VM側で作ったファイルがhost側でも見れているので共有できていそう。

## 設定修正後のVagrantfileの確認
```bash: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"
  config.vm.synced_folder "./data", "/home/vagrant/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
    vb.gui = false
  #
  #   # Customize the amount of memory on the VM:
  #   vb.memory = "1024"
    vb.memory = "2048"
    vb.cpus = "2"
    vb.name = "testVM"
  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
  # Ansible, Chef, Docker, Puppet and Salt 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

```

**これらの設定は　``vagrant up``or ``vagrant reload``　コマンドでVMを立ち上げる度に即時反映されます。**
これ結構大事かも。

## VMの削除
VM停止中に以下の流れで実行。

```zsh
$ vagrant global-status
id       name    provider   state    directory
-------------------------------------------------------------------------
72458cf  default virtualbox poweroff /Users/user/work/vagrant/centos7

The above shows information about all known Vagrant environments
on this machine. This data is cached and may not be completely
up-to-date (use "vagrant global-status --prune" to prune invalid
entries). To interact with any of the machines, you can go to that
directory and run Vagrant, or you can use the ID directly with
Vagrant commands from any directory. For example:
"vagrant destroy 1a2b3c4d"
$
$ vagrant destroy 72458cf
    default: Are you sure you want to destroy the 'default' VM? [y/N] y
==> default: Destroying VM and associated drives...
$
```
Virtualbox を確認して削除されていることを確認。
<img width="952" alt="スクリーンショット 2020-08-01 15.22.03.png" src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/373211/ed8eb60c-1b1c-06ec-bb2a-9510a42de0f3.png">

# アウトロ
まだまだ設定できる事は多いと思うがとりあえずここまでやればとりあえず使えるようになるかと。
今後も自分が設定を追加で変更した時は、この記事にも反映していこうと思います。
ここで基本的な設定をした後にansibleを使ってもっと細かい設定をすれば環境構築は完璧だと思います。
ansibleは現在勉強中なので、ある程度わかってきたらまたまとめ記事を出そうかなと思います。
最後まで御覧頂きありがとうございました。

# 参考にさせて頂いたありがたい先人のURL
[MacにVagrantでCentOS7環境を作成](https://qiita.com/sudachi808/items/3614fd90f9025973de4b)
[Vagrant入門③〜Vagrantfile設定編](https://qiita.com/akippa_app/items/d6aef518bff20dc39530)