Tech Tips

  1. プログラミング
  2. 799 view

Windows上で Vagrant + Ansible を使ってテスト用Webサーバ構築

vagrant
Vagrantを使うことで仮想マシンを立ち上げることができる。Ansibleを使うことで立ち上げたマシンにソフトウェアをインストールさせたり、アプリをデプロイさせたりすることができる。本記事ではこれらのツールを使って、テスト用のWebサーバを立てる方法を紹介する。構築するWebサーバはNginxが入っているだけの簡単なもので、ブラウザからアクセスできるところまで試す。

環境

  • OS
    • Windows7 Enterprise Service Pack1
  • Vagrant
    • 1.7.4
  • Virtual Box
    • 4.3.26

環境構築

以下の手順で簡単に環境構築できる。
  1. 公式サイトからVirtual Boxインストーラをダウンロードしてインストールする。
  2. 公式サイトからVagrantインストーラをダウンロードしてインストールする。

仮想マシンの構築・起動

環境構築が完了したため、次にVagrantから仮想マシンを構築・起動させてみる。

1. ディストリビューションの選定

Vagrant用に用意されたディストリビューションの中から好きなものを選ぶ。
本記事では、”Official Ubuntu 14.04 daily Cloud Image i386 (Development release, No Guest Additions)”を利用する。
※64bit版を利用する場合は仮想化支援機構をBIOSから有効にする必要がある。PCメーカごとに設定方法が異なる。

2. 構築・起動

1で選んだディストリビューションのURLをコピーして、コマンドプロンプトを立ち上げる。
コマンドプロンプトで以下のコマンドを叩く。
# Vagrantにディストリビューションを追加
C:\Users\...\Desktop>vagrant box add ubuntu14.04i386 https://cloud-images.ubuntu.com/vagrant/trusty/current/trusty-server-cloudimg-i386-vagrant-disk1.box

==> box: Box file was not detected as metadata. Adding it directly...
==> box: Adding box 'ubuntu14.04i386' (v0) for provider:
    box: Downloading: https://cloud-images.ubuntu.com/vagrant/trusty/current/tru
sty-server-cloudimg-i386-vagrant-disk1.box
    box: Progress: 100% (Rate: 1311k/s, Estimated time remaining: --:--:--)
==> box: Successfully added box 'ubuntu14.04i386' (v0) for 'virtualbox'!

# 仮想マシン構築用ファイル(Vagrantfile)の作成
C:\Users\...\Desktop>vagrant init ubuntu14.04i386
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.

# 仮想マシンの構築と起動
C:\Users\...\Desktop>vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'ubuntu14.04i386'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: Desktop_default_1442904841403_7922
==> 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: Forwarding ports...
    default: 22 => 2222 (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: Connection timeout. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
    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: Mounting shared folders...
    default: /vagrant => C:/Users/...Desktop
ここまで来れば仮想マシンはもう起動しているため、次でsshアクセスする。

3. 仮想マシンへのアクセス

Putty setting for vagrant
本記事ではsshアクセスにputtyを利用する。
puttyの場合は以下のように設定して「Open」ボタンをクリックすれば接続できる。
「Open」ボタンをクリックしたあとにポップアップが出てきた場合は、「OK」ボタンを押せば大丈夫。
以下のユーザ名とパスワードでログインできる。
  • ユーザ名:vagrant
  • パスワード:vagrant
login as: vagrant
vagrant@127.0.0.1's password:
Welcome to Ubuntu 14.04.3 LTS (GNU/Linux 3.13.0-63-generic i686)

 * Documentation:  https://help.ubuntu.com/

 System information disabled due to load higher than 1.0

  Get cloud support with Ubuntu Advantage Cloud Guest:
    http://www.ubuntu.com/business/services/cloud

0 packages can be updated.
0 updates are security updates.

vagrant@vagrant-ubuntu-trusty-32:~$
後はもうubuntu14.04なので、「sudo apt-get install」コマンドで好きなソフトウェアをインストールできる。 以下のコマンドで仮想マシンを停止させたりできる。
  • サスペンド:vagrant suspend
  • 停止:vagrant halt
  • 再起動:vagrant up
  • ステータス確認:vagrant status

AnsibleでWebサーバ構築

次にAnsibleを使って、仮想マシン起動時にnginxのインストールを行わせる。

1. 環境準備

いくつかファイルの準備が必要であるため、適当な場所にディレクトリを作る。
最終的には、以下のようなディレクトリ構成になる。
用意するファイルは、基本的には、
template-vagrantを参考にして用意する。
.
|-ansible
|  |-hosts
|   -playbook.yml
|-provision.sh
 -Vagrantfile

2. Vagrantfileの設定

Vagrantfileは先程作ったものをコピーするか、
用意したディレクトリ上で「vagrant init ubuntu14.04i386」コマンドを叩く。 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 = "ubuntu14.04i386"

  # 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
  #   sudo apt-get update
  #   sudo apt-get install -y apache2
  # SHELL

  config.vm.provision "shell", :path => "provision.sh"
  config.vm.synced_folder ".", "/vagrant", :mount_options => ['dmode=775', 'fmode=664']
end

3. provision.sh/hosts/playbook.ymlの用意

それぞれ以下のように記述する。
  1. provision.sh
    #!/usr/bin/env bash
    
    
    if ! [ `which ansible` ]; then
    	apt-get update -y
    	apt-get install -y ansible
    fi
    
    ansible-playbook -i /vagrant/ansible/hosts /vagrant/ansible/playbook.yml
    
  2. hosts
    127.0.0.1 ansible_connection=local
    
  3. playbook.yml
    ---
    - hosts: 127.0.0.1
      connection: local
      sudo: yes
      tasks:
        - name: install nginx
          apt: pkg=nginx update_cache=yes
    

4. 動作確認

以下のように用意したディレクトリ上で「vagrant up」を叩く。
C:\Users\...\Desktop\vagrant>vagrant up

Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'ubuntu14.04i386'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: vagrant_default_1442906425474_82960
==> 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: 22 => 2222 (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: Connection timeout. Retrying...
    default: Warning: Connection timeout. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
    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: Configuring and enabling network interfaces...
==> default: Mounting shared folders...
    default: /vagrant => C:/Users/hidetomo.suzuki/Desktop/vagrant
==> default: Running provisioner: shell...
    default: Running: C:/Users/.../AppData/Local/Temp/vagrant-shell2015
0922-7688-1m4rfud.sh
==> default: stdin: is not a tty
==> default: Ign http://security.ubuntu.com trusty-security InRelease
==> default: Ign http://archive.ubuntu.com trusty InRelease
==> default: Get:1 http://security.ubuntu.com trusty-security Release.gpg [933 B
]
==> default: Get:2 http://security.ubuntu.com trusty-security Release [63.5 kB]
==> default: Ign http://archive.ubuntu.com trusty-updates InRelease
==> default: Hit http://archive.ubuntu.com trusty Release.gpg
==> default: Get:3 http://archive.ubuntu.com trusty-updates Release.gpg [933 B]
==> default: Get:4 http://security.ubuntu.com trusty-security/main Sources [94.6
 kB]
==> default: Hit http://archive.ubuntu.com trusty Release
==> default: Get:5 http://archive.ubuntu.com trusty-updates Release [63.5 kB]
==> default: Get:6 http://security.ubuntu.com trusty-security/universe Sources [
30.5 kB]
==> default: Get:7 http://security.ubuntu.com trusty-security/main i386 Packages
 [328 kB]
==> default: Get:8 http://security.ubuntu.com trusty-security/universe i386 Pack
ages [116 kB]
==> default: Hit http://security.ubuntu.com trusty-security/main Translation-en
==> default: Get:9 http://archive.ubuntu.com trusty/main Sources [1,064 kB]
==> default: Hit http://security.ubuntu.com trusty-security/universe Translation
-en
==> default: Get:10 http://archive.ubuntu.com trusty/universe Sources [6,399 kB]

==> default: Hit http://archive.ubuntu.com trusty/main i386 Packages
==> default: Hit http://archive.ubuntu.com trusty/universe i386 Packages
==> default: Hit http://archive.ubuntu.com trusty/main Translation-en
==> default: Hit http://archive.ubuntu.com trusty/universe Translation-en
==> default: Get:11 http://archive.ubuntu.com trusty-updates/main Sources [234 k
B]
==> default: Get:12 http://archive.ubuntu.com trusty-updates/universe Sources [1
36 kB]
==> default: Get:13 http://archive.ubuntu.com trusty-updates/main i386 Packages
[601 kB]
==> default: Get:14 http://archive.ubuntu.com trusty-updates/universe i386 Packa
ges [314 kB]
==> default: Hit http://archive.ubuntu.com trusty-updates/main Translation-en
==> default: Hit http://archive.ubuntu.com trusty-updates/universe Translation-e
n
==> default: Ign http://archive.ubuntu.com trusty/main Translation-en_US
==> default: Ign http://archive.ubuntu.com trusty/universe Translation-en_US
==> default: Fetched 9,445 kB in 45s (206 kB/s)
==> default: Reading package lists...
==> default: Reading package lists...
==> default: Building dependency tree...
==> default: Reading state information...
==> default: The following extra packages will be installed:
==> default:   python-jinja2 python-markupsafe
==> default: Suggested packages:
==> default:   ansible-doc sshpass python-jinja2-doc
==> default: The following NEW packages will be installed:
==> default:   ansible python-jinja2 python-markupsafe
==> default: 0 upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
==> default: Need to get 593 kB of archives.
==> default: After this operation, 3,846 kB of additional disk space will be use
d.
==> default: Get:1 http://archive.ubuntu.com/ubuntu/ trusty/main python-markupsa
fe i386 0.18-1build2 [14.3 kB]
==> default: Get:2 http://archive.ubuntu.com/ubuntu/ trusty/main python-jinja2 a
ll 2.7.2-2 [161 kB]
==> default: Get:3 http://archive.ubuntu.com/ubuntu/ trusty/universe ansible all
 1.5.4+dfsg-1 [418 kB]
==> default: dpkg-preconfigure: unable to re-open stdin: No such file or directo
ry
==> default: Fetched 593 kB in 17s (34.5 kB/s)
==> default: Selecting previously unselected package python-markupsafe.
==> default: (Reading database ... 61102 files and directories currently install
ed.)
==> default: Preparing to unpack .../python-markupsafe_0.18-1build2_i386.deb ...

==> default: Unpacking python-markupsafe (0.18-1build2) ...
==> default: Selecting previously unselected package python-jinja2.
==> default: Preparing to unpack .../python-jinja2_2.7.2-2_all.deb ...
==> default: Unpacking python-jinja2 (2.7.2-2) ...
==> default: Selecting previously unselected package ansible.
==> default: Preparing to unpack .../ansible_1.5.4+dfsg-1_all.deb ...
==> default: Unpacking ansible (1.5.4+dfsg-1) ...
==> default: Processing triggers for man-db (2.6.7.1-1ubuntu1) ...
==> default: Setting up python-markupsafe (0.18-1build2) ...
==> default: Setting up python-jinja2 (2.7.2-2) ...
==> default: Setting up ansible (1.5.4+dfsg-1) ...
==> default:
==> default: PLAY [127.0.0.1] **************************************************
************
==> default:
==> default: GATHERING FACTS ***************************************************
************
==> default: ok: [127.0.0.1]
==> default:
==> default: TASK: [install nginx] *********************************************
==> default: Suggested packages:
==> default:   ansible-doc sshpass python-jinja2-doc
==> default: The following NEW packages will be installed:
==> default:   ansible python-jinja2 python-markupsafe
==> default: 0 upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
==> default: Need to get 593 kB of archives.
==> default: After this operation, 3,846 kB of additional disk space will be use
d.
==> default: Get:1 http://archive.ubuntu.com/ubuntu/ trusty/main python-markupsa
fe i386 0.18-1build2 [14.3 kB]
==> default: Get:2 http://archive.ubuntu.com/ubuntu/ trusty/main python-jinja2 a
ll 2.7.2-2 [161 kB]
==> default: Get:3 http://archive.ubuntu.com/ubuntu/ trusty/universe ansible all
 1.5.4+dfsg-1 [418 kB]
==> default: dpkg-preconfigure: unable to re-open stdin: No such file or directo
ry
==> default: Fetched 593 kB in 17s (34.5 kB/s)
==> default: Selecting previously unselected package python-markupsafe.
==> default: (Reading database ... 61102 files and directories currently install
ed.)
==> default: Preparing to unpack .../python-markupsafe_0.18-1build2_i386.deb ...

==> default: Unpacking python-markupsafe (0.18-1build2) ...
==> default: Selecting previously unselected package python-jinja2.
==> default: Preparing to unpack .../python-jinja2_2.7.2-2_all.deb ...
==> default: Unpacking python-jinja2 (2.7.2-2) ...
==> default: Selecting previously unselected package ansible.
==> default: Preparing to unpack .../ansible_1.5.4+dfsg-1_all.deb ...
==> default: Unpacking ansible (1.5.4+dfsg-1) ...
==> default: Processing triggers for man-db (2.6.7.1-1ubuntu1) ...
==> default: Setting up python-markupsafe (0.18-1build2) ...
==> default: Setting up python-jinja2 (2.7.2-2) ...
==> default: Setting up ansible (1.5.4+dfsg-1) ...
==> default:
==> default: PLAY [127.0.0.1] **************************************************
************
==> default:
==> default: GATHERING FACTS ***************************************************
************
==> default: ok: [127.0.0.1]
==> default:
==> default: TASK: [install nginx] *********************************************
Nginx on vagrant
このように出力されていたら成功。
ブラウザで「http://192.168.33.10/」にアクセスすると以下のように
nginxの初期設定のindex.htmlが表示される。

参考サイト

  1. Windows 7マシンで、VirtualBox+Vagrantを使いUbuntu 14.04を動かす
  2. Vagrant と Ansible で Windows でも快適開発
  3. Windows上でVirtualBox+Vagrant+CentOSによる仮想環境構築

プログラミングの最近記事

  1. PubSubClient の便利さと注意点

  2. Java の環境構築方法メモ

  3. PlatformIO IDE for VSCode を使用して VSCode で Ardu…

  4. ROS Docker イメージで発生した GPG error の解消方法

  5. Streamlit で訪れた国を色づけした世界地図を作成できるアプリケーションを作成してみ…

関連記事

PAGE TOP