Vagrantを触ってみる

Vagrantと言えば Mitchell Hashimotoさんが開発した仮想マシン環境構築ソフトです。Mitchell Hashimoto さんと言えば HashiCorpの設立者で、Packer, Serf, Consul等、色々な素晴らしいソフトを作っていますよね。

さて、その第一弾となった Vagrantですが、今まであまり使う機会が無かったので触れておきたいなと思いました。今更感は半端ないですが、それ考えると先進まないので思考停止して行ってみよー!

公式サイト

何を始めるにしても公式サイトを見るのが楽だよね。
というわけで、この記事でも公式サイトの流れを追う感じで書いていこうと思います。
www.vagrantup.com

役割

仮想マシンをファイルベースで作成

  1. 設定をコード化できる
  2. 設定を再現出来る
  3. 設定を持ち運べる

手順

1. Vagrantのインストール (公式サイト参照)

環境に応じたインストール手順でインストールしてね
僕は homebrewを使った様な気がする (覚えてない)
www.vagrantup.com

2. Vagrantファイルの作成

vagrant initVagrantファイルのテンプレートを作成してくれます

$ vagrant init hashicorp/precise64
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.

終わると Vagrantファイルが作成されているのが分かります

$ ls
Vagrantfile

中身はこんな感じです

$ less 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://atlas.hashicorp.com/search.
  config.vm.box = "hashicorp/precise64"

  # 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.
  # config.vm.network "forwarded_port", guest: 80, host: 8080

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

  # Define a Vagrant Push strategy for pushing to Atlas. Other push strategies
  # such as FTP and Heroku are also available. See the documentation at
  # https://docs.vagrantup.com/v2/push/atlas.html for more information.
  # config.push.define "atlas" do |push|
  #   push.app = "YOUR_ATLAS_USERNAME/YOUR_APPLICATION_NAME"
  # end

  # 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

3. 仮想マシンプロバイダ上にマシンの配置

vagrant upにて実施

ログを見ると色々やっているのが分かりますね

  • 指定仮想マシンのインポート
  • NATやネットワーク周りの設定
  • ポートフォワーディングの設定
  • Boxの更新確認
  • VMの起動
  • 共有フォルダのマウント
$ vagrant up
==> default: Importing base box 'hashicorp/precise64'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'hashicorp/precise64' is up to date...
==> default: Setting the name of the VM: new_default_1476494705030_32930
==> 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: Warning: Remote connection disconnect. 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: 4.2.0
    default: VirtualBox Version: 5.0
==> default: Mounting shared folders...
    default: /vagrant => /Users/xxxx/work/study/vagrant/new

4. ログイン
vagrant sshで完成した仮想マシンにログインできます

$ vagrant ssh
Welcome to Ubuntu 12.04 LTS (GNU/Linux 3.2.0-23-generic x86_64)

 * Documentation:  https://help.ubuntu.com/
New release '14.04.5 LTS' available.
Run 'do-release-upgrade' to upgrade to it.

Welcome to your Vagrant-built virtual machine.
Last login: Fri Sep 14 06:23:18 2012 from 10.0.2.2
vagrant@precise64:~$ ls
postinstall.sh
vagrant@precise64:~$ pwd
/home/vagrant
vagrant@precise64:~$ exit
logout

5. SSHクライアントからログイン
sshコマンドや putty/Teratermの様なクライアントからのログインも可能です

先ずはvagrant ssh-configで接続設定を確認します

$ vagrant ssh-config
Host default
  HostName 127.0.0.1
  User vagrant
  Port 2222
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile 
  /Users/xxx/work/study/vagrant/new/.vagrant/machines/default/virtualbox/private_key
  IdentitiesOnly yes
  LogLevel FATAL

続けて確認した設定に基づいて Host, Port, ユーザ, 秘密鍵を指定すればログインできます

ホスト 127.0.0.1
ポート 2222
ユーザ vagrant
秘密鍵 ~/work/study/vagrant/new/.vagrant/machines/default/virtualbox/private_key
$ ssh vagrant@127.0.0.1 -p 2222 \
  -i ~/work/study/vagrant/new/.vagrant/machines/default/virtualbox/private_key
The authenticity of host '[127.0.0.1]:2222 ([127.0.0.1]:2222)' can't be established.
ECDSA key fingerprint is SHA256:+zgKqxyYlTBAs0xtTVGxxxxxS9Zr71wQGvnG/k2igw.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[127.0.0.1]:2222' (ECDSA) to the list of known hosts.
Welcome to Ubuntu 12.04 LTS (GNU/Linux 3.2.0-23-generic x86_64)

 * Documentation:  https://help.ubuntu.com/
New release '14.04.5 LTS' available.
Run 'do-release-upgrade' to upgrade to it.

Welcome to your Vagrant-built virtual machine.
Last login: Sat Oct 15 02:12:55 2016 from 10.0.2.2