見出し画像

Vagrantfileの基本的な書き方

前回はVirtualBoxとVagrantでCentOS8のイメージを取得してSSH接続するところまで行いました

その中でvagrant initコマンドでVagrantfileを生成していましたが、その中身をみていこうと思います

% ls -alt
total 8
-rw-r--r--  1 k  staff  3021  8  9 02:28 Vagrantfile
drwxr-xr-x  4 k  staff   128  8  9 02:28 .
drwxr-xr-x  4 k  staff   128  8  8 20:35 .vagrant
drwxr-xr-x  3 k  staff    96  8  8 20:31 ..
% 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 = "generic/centos8"

 # 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

生成したての状態だと上記のようになります

記法としてはRubyのような構文になっていますね(Rubyを使ったことはないですがなんとなくは読めそうです)



Vagrantfileとは

Vagrantfileとは何ぞやということに関しては公式の説明を参考に重要そうな部分をピックアップしてみました

1. Vagrantfileはプロジェクトに必要なマシンタイプや、どのような構成か、どのように配布するかを記述したファイル

2. プロジェクトごとに1つのVagrantfileで動く

3. Vagrantfileはバージョン管理すべきである(プロジェクトに参画している他の開発者がコードをチェックアウトし、vagrant runコマンドを実行し、同じ環境で作業を行っていけるようにするため)

4. VagrantfileはRubyの記法だがRubyの知識はそこまで必要ない



構成ファイルのバージョン

vagrant initコマンドでVagrantfileを生成すると

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

といったフォーマットで記述されるがこれは「バージョン2」ということ(2020/08/09現在)



config.vm

詳しくはconfig.vmの説明ページ参照

よく使いそうなものを列挙してみます

1. box

型 : string

どのBoxを使うかを指定

init時は自動でaddしたBoxが指定される

config.vm.box = "generic/centos8"


2. box_version

型 : string

Boxのバージョン指定

デフォルトは">= 0"で、最新を取得する

config.vm.box_version = "3.0.22"


3. hostname

型 : string

マシンのホストネームを指定

デフォルトだとnil

指定するとゲストの/etc/hostsに書き込まれる

config.vm.hostname = "hoge"


4. synced_folder

型 : string

ホストマシンとゲストマシンでフォルダの共有を行う

config.vm.synced_folder "src/", "/srv/website"

第一引数 : ホストマシンのパス・相対パスだとプロジェクトルートパス

第二引数 : ゲストマシンのパス・必ず絶対パス指定

ディレクトリは再起的に生成される

マウントする際の設定一覧

create : boolean = デフォルトはfalse、trueにするとホスト側に指定フォルダがない場合は作成

disabled : boolean = デフォルトはfalse、trueにするとフォルダ共有を行わない(前の設定を残しておくなどの用途)

group : string = 同期フォルダの所有グループを指定。デフォルトはSSHユーザー

owner : string = 同期フォルダの所有ユーザーを指定。デフォルトはSSHユーザー

config.vm.synced_folder "src/", "/srv/website",
 owner: "root", group: "root"

type : string = 同期フォルダタイプを指定。デフォルトはnfs

mount_options : array = マウント時のフォルダ設定などが可能。配列形式で記述していく

mount_options: ["uid=1234", "gid=1234", "dmode=777","fmode=755"]


5. network

型 : string

読んで字のごとく、ネットワーク設定

forwarded_port : ホストマシンからゲストマシンへポートフォワードする際の設定

guest : int = ゲスト側のポート設定。必須項目

host : int = ホスト側のポート設定。必須項目

id : string = VirtualBoxから見ることができるポートフォワードのルール名

protocol : string = プロトコルの設定。"udp"か"tcp"を設定。デフォルトは"tcp"

Vagrant.configure("2") do |config|
 config.vm.network "forwarded_port", guest: 80, host: 8080, id: "tcp123", protocol: "tcp"
end


private_network : プライベートネットワークアドレスに関する設定

Vagrant.configure("2") do |config|
 config.vm.network "private_network", ip: "192.168.50.4"
end


public_network : パブリックネットワークアドレスに関する設定

割愛


6. provision

型 : string

vagrant upした際に自動でソフトウェアをインストールするなどシェルを実行したりする際の設定

オプションは下記のものとなる

type : string = shellかfileを設定(詳細は別記事にまとめようと思います)




動作確認で使用するVagrantfile

今回動作確認で使用するVagrantfileについてはこんなお試しのものを作ってみたので下記の設定で使用することにします

% 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 = "generic/centos8"
 config.vm.box_version = "3.0.22"
 config.vm.hostname = "host01"

 # 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, protocol: "tcp"

 # 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.50.4"

 # 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 "src/", "/vagrant_data",
   owner: "vagrant", group: "vagrant",
   mount_options: ["dmode=777", "fmode=755"]

 # 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
   echo "hello world!"
 SHELL
end



起動・検証

vagrant up --provisionで出力されるログで確認

% vagrant up --provision
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Checking if box 'generic/centos8' version '3.0.22' is up to date...
==> default: Clearing any previously set forwarded ports...
==> 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: 80 (guest) => 8080 (host) (adapter 1)
   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: 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 r139111
   default: VirtualBox Version: 6.1
==> default: Setting hostname...
==> default: Configuring and enabling network interfaces...
==> default: Mounting shared folders...
   default: /vagrant_data => /Users/k/vagrant/centos8/src
==> default: Running provisioner: shell...
   default: Running: inline script
   default: hello world!


ちゃんと指定したバージョンが適用されてそうですね

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


srcが/vagrant_dataにマウントされてそうです

後でssh接続して確認します

==> default: Mounting shared folders...
   default: /vagrant_data => /Users/k/vagrant/centos8/src


provisionで設定したshellが実行されていることが確認できました

==> default: Running provisioner: shell...
   default: Running: inline script
   default: hello world!


次にssh接続して設定が反映されているか確認します

% vagrant ssh
Last login: Sun Aug  9 10:36:51 2020 from 10.0.2.2

[vagrant@host01 ~]$

ホスト名がhost01に設定されているようですね


正常にマウントされているかどうか確認します

まずはホスト側のファイルがどうなっているかというと以下のようになっています

% tree
.
├── Vagrantfile
└── src
   └── file
1 directory, 2 files

これがゲストマシンの/vagrant_dataにあればOKです

[vagrant@host01 /]$ find / -maxdepth 1 -name vagrant_data -type d -ls
       0      0 drwxrwxrwx   1  vagrant  vagrant        96 Aug  9 10:44 /vagrant_data

/vagrant_dataが存在してsynced_folderの設定通りパーミッションは777になってそうです

[vagrant@host01 /]$ cd /vagrant_data/
[vagrant@host01 vagrant_data]$ ls -l
total 4
-rwxr-xr-x. 1 vagrant vagrant 4 Aug  9 10:44 file

ファイルが存在することが確認できました!


最後にプライベートIPが設定されているか確認します

[vagrant@host01 vagrant_data]$ ip -4 a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
   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 fq_codel state UP group default qlen 1000
   inet 10.0.2.15/24 brd 10.0.2.255 scope global dynamic noprefixroute eth0
      valid_lft 84351sec preferred_lft 84351sec
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
   inet 192.168.50.4/24 brd 192.168.50.255 scope global noprefixroute eth1
      valid_lft forever preferred_lft forever

192.168.50.4が適用されているようです


最後に

簡単にVagrantfileについてまとめてみましたが、provisionのshellであったりfileであったりがまだ中途半端なので後日また記事にできたらなと思っています

この記事が気に入ったらサポートをしてみませんか?