Total Pageviews

Friday, 13 May 2016

用 Vagrant统一开发环境

WHY VAGRANT?

Vagrant provides easy to configure, reproducible, and portable work environments built on top of industry-standard technology and controlled by a single consistent workflow to help maximize the productivity and flexibility of you and your team.
To achieve its magic, Vagrant stands on the shoulders of giants. Machines are provisioned on top of VirtualBox, VMware, AWS, or any other provider. Then, industry-standard provisioning tools such as shell scripts, Chef, or Puppet, can be used to automatically install and configure software on the machine.
——以上内容摘自官网
因其是使用虚拟机的,所以虚拟机的好处全部都有,你可以随便折腾,弄得不爽了可以马上复原,真的是很方便。 也简化了操作虚拟机的步骤,一条命令即可创建一个虚拟系统,即开即用

安装

添加 Box

Box 理解为一个打包好的操作系统环境就好了
可以自己做,也可以直接下载制作好的
Vargrant 将 box 解包后放在 /.vagrant.d/boxes 文件夹

通过命令直接下载

例如下载 Ubuntu 官方创建的 Ubuntu Server 64-bit 14.04 的 box
其中的 Ubuntu Server 64-bit 14.04 是自己设定的 box 名字
vagrant box add Ubuntu_Server_14.04 ubuntu/trusty64
Box 可以去 Vagrant Cloud

手动下载 box

例如下载 Ubuntu 的 box, 下载完成之后添加一下 box
vagrant box add Ubuntu_Server_14.04 ~/Inbox/trusty-server-cloudimg-amd64-vagrant-disk1.box

自己制作 base box

第一次使用 Vagrant 建议跳过这一步骤,到下一步, 直接使用制作好的 base box, 体会了 Vagrant 之后再来自己制作 base box
人家制作好的 box 或许没有你需要的,那么就需要自己来制作了

使用 Veewee 工具创建(虚拟机为 Parallels)

  1. 安装好 Ruby 之后,用如下命令安装 Veewee
    gem install veewee
  2. 查看支持的模板
    veewee parallels templates
(未完成,博主还没有实践,或许以后会补全)

手动创建(虚拟机为 Parallels)

  1. 在 Parallels 中新建一个虚拟机,比如名字为 Ubuntu-14.04.2-vagrant
    把不需要的功能都关闭了,比如共享应用什么的,硬件配置自己选择合适的
    以下是推荐系统设置
    Root Password: vagrant
    Main account login: vagrant
    Main account password: vagrant
  2. 安装一些必要的软件,例如 Parallels Tools, SSH
    以下是安装 SSH 的方法
    1. 先去 insecure keypair 下载 Vagrant 的公钥,名为 vagrant.pub
      或者使用命令
      wget https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub
    2. 安装 SSH 服务
      sudo apt-get update
      sudo apt-get install openssh-server
    3. 添加 Vagrant 的公钥
      mkdir ~/.ssh
      chmod 700 ~/.ssh
      touch ~/.ssh/authorized_keys
      chmod 600 ~/.ssh/authorized_keys
      cat vagrant.pub >> ~/.ssh/authorized_keys
  3. 安装一些基本的软件,例如 git, vim, zsh, oh-my-zsh 等
    安装完软件之后清理一下软件包
    sudo apt-get clean
  4. 让 Vagrant 用户使用 sudo 时不需要输入密码(必须,要不然一些 Vagrant 的功能无法实现)
    先输入命令 sudo visudo, 然后在末尾添加一行,内容如下
    vagrant ALL=(ALL) NOPASSWD: ALL
  5. 关闭虚拟机
    进入虚拟机目录,例如:~/Documents/Parallels/Ubuntu-14.04.2-vagrant.pvm, 可看到一些文件和文件夹,其中需要的是以下 3 个文件和文件夹,其它的可删除
    VmInfo.pvi
    config.pvs
    *.hdd
    可对虚拟磁盘进行优化,减少大小
    prl_disk_tool compact --hdd *.hdd
  6. 打包成 base box
    还需要 Vagrantfile 和 metadata.json 文件, Vagrantfile 文件内容可为空,metadata.json 可如下所示
    {"provider":"parallels"}
    然后进行打包
    tar cvzf Ubuntu-14.04.2-parallels.box ./Ubuntu-14.04.2-vagrant.pvm ./Vagrantfile ./metadata.json
  7. 做好了 base box 自己得测试一下

参考资料:
CREATING A BASE BOX | Vagrant
Creating a Base Box | Parallels

初始化和配置

  1. 建立一个 Vagrant 项目目录
    mkdir ~/Vagrant
  2. 初始化一个项目
    cd ~/Vagrant
    mkdir Ubuntu_Server_14.04
    cd Ubuntu_Server_14.04
    vagrant box list    # 列出现有的 box
    vagrant init Ubuntu_Server_14.04
    会在当前目录下生成一个 Vagrantfile 文件,用于描述你的项目(虚拟机的网络连接方式,同步文件夹等)

Vagrantfile 配置文件

配置文件是用 Ruby 写的,不过都是一些常用的赋值
文件内部的解释非常清晰,就不班门弄斧了
对于 Parallels 虚拟机可进行如下配置:
# 设置端口转发,将主机的 8081 端口转发到虚拟机的 80 端口,在开发 Web 应用的时候非常有用
config.vm.network "forwarded_port", guest: 80, host: 8081

# 将主机的 /Users/mwum/Code 文件夹共享到虚拟机的 /home/vagrant/Code 文件夹
config.vm.synced_folder "/Users/mwum/Code", "/home/vagrant/Code"

config.vm.provider "parallels" do |v|
  # Virtual Machine Name
  v.name = "Ubuntu-14.04-parallels"
  # Parallels Tools Auto-Update
  v.update_guest_tools = true
  # Memory
  # v.memory = 1024
end

默认共享目录

默认主机的项目目录和虚拟机中的 /vagrant 目录是共享的

使用

以下命令在项目目录中执行
  • vagrant up - 启动虚拟机,如果一个项目第一次执行,它会初始化一个虚拟机
  • vagrant ssh - 连接虚拟机
  • vagrant halt - 关闭虚拟机,普通的关机
  • vagrant suspend - 关闭虚拟机,类似休眠
  • vagrant reload - 重启虚拟机
  • vagrant destroy - 删除虚拟机,虚拟机没了但是 box 还在
更多命令请看《官方文档 - COMMAND-LINE INTERFACE

打包成 box

当你自定义了开发环境之后,在项目目录执行命令
vagrant package
在此目录会生成一个 package.box 文件,将这个 box 给其它开发人员,就能保证你们的开发环境相同了
或者使用命令 vagrant package -h 查看更详尽的用法,例如使用
vagrant package --include readme.txt --vagrantfile Vagrantfile
但是发现个问题,下次使用 vagrant box addvagrant init 添加和初始化好这个 box 之后, 然后使用 vagrant up 会出现警告大致是说 .vagrant.d/boxes/boxname/0/virtualbox/include/_Vagrantfile:5: warning: already initialized constant VAGRANTFILE_API_VERSION, 出现这个问题的原因呢就是项目的当前目录有个 Vagrantfile, 并且我们用上面的命令把 Vagrantfile 也添加到了 box 中
解决的办法就是,如果要用 box 中的 Vagrantfile 那么把 .vagrant.d/boxes/boxname/0/virtualbox/include/_Vagrantfile 文件重命名为 Vagrantfile 并覆盖项目目录中的 Vagrantfile; 如果不用它,那么将其删除

自动化

若想统一开发环境和生产环境也是可以的,将虚拟机系统环境配置成相同的环境即可
若想让两个环境完全一样,并实现自动化配置,可以尝试Chef或Puppet

心得

使用一段时间这个环境之后:Mac + VirtualBox + Vagrant
有个问题,使用 Public Networks 网络方式的时候,与外网的连接不是很好
而且我还用着 Parallels 虚拟机,于是尝试了 vagrant-parallels 插件,使之能用 Vagrant 来管理 Parallels 虚拟机
官方文档:http://parallels.github.io/vagrant-parallels/docs/
当使用 Vagrant 启动 Parallels 虚拟机的时候,会出现 Gui 窗口,为了关闭这个窗口可以按如下操作:
执行 prlctl set <name> --on-window-close keep-running 命令之后,即使把窗口关了,虚拟机也在后台运行
使用了一段时间,在 VirtualBox 中的问题没有遇到过,也没有遇到其它问题。 而且 Parallels 虚拟机的性能比 VirtualBox 虚拟机要好.
-----------

Vagrant is a tool for building and distributing development environments. 

Vagrant

Vagrant is a tool for building and distributing development environments.
Development environments managed by Vagrant can run on local virtualized platforms such as VirtualBox or VMware, in the cloud via AWS or OpenStack, or in containers such as with Docker or raw LXC.
Vagrant provides the framework and configuration format to create and manage complete portable development environments. These development environments can live on your computer or in the cloud, and are portable between Windows, Mac OS X, and Linux.

Quick Start

For the quick-start, we'll bring up a development machine on VirtualBox because it is free and works on all major platforms. Vagrant can, however, work with almost any system such as OpenStackVMwareDocker, etc.
First, make sure your development machine has VirtualBox installed. After this, download and install the appropriate Vagrant package for your OS.
To build your first virtual environment:
vagrant init hashicorp/precise32
vagrant up
Note: The above vagrant up command will also trigger Vagrant to download the precise32 box via the specified URL. Vagrant only does this if it detects that the box doesn't already exist on your system.

Getting Started Guide

To learn how to build a fully functional development environment, follow the getting started guide.

Installing the Gem from Git

If you want the bleeding edge version of Vagrant, we try to keep master pretty stable and you're welcome to give it a shot. The following is an example showing how to do this:
rake install
Ruby 2.2 is needed.

Contributing to Vagrant

To install Vagrant from source, please follow the guide in the Wiki.
You can run the test suite with:
bundle exec rake
This will run the unit test suite, which should come back all green! Then you're good to go!
If you want to run Vagrant without having to install the gem, you may use bundle exec, like so:
bundle exec vagrant help
NOTE: By default running Vagrant via bundle will disable plugins. This is necessary because Vagrant creates its own private Bundler context (it does not respect your Gemfile), because it uses Bundler to manage plugin dependencies.

Acceptance Tests

Vagrant also comes with an acceptance test suite that does black-box tests of various Vagrant components. Note that these tests are extremely slow because actual VMs are spun up and down. The full test suite can take hours. Instead, try to run focused component tests.
To run the acceptance test suite, first copy vagrant-spec.config.example.rb to vagrant-spec.config.rb and modify it to valid values. The places you should fill in are clearly marked.
Next, see the components that can be tested:
$ rake acceptance:components
cli
provider/virtualbox/basic
...
Then, run one of those components:
$ rake acceptance:run COMPONENTS="cli"
...
from https://github.com/mitchellh/vagrant
----------------------------------------------

Vagrant 简单使用 

一. 安装

Vagrant 本质上来说,是对 virtualbox,vmware,kvm 等镜像的管理操作,是一个中间层技术。使用它的前提是你本机必须有 virtualbox,vmware,kvm 等虚拟机。

Vagrant 的安装非常简单,各个 linux 发行版可以直接通过包管理安装,OS X 也可以通过 Homebrew Cask来安装。

$ brew cask install vagrant

建立你自己的 Vagrant 也非常简单,

$ mkdir /your/path/vagrant_name; cd /your/path/vagrant_name; vagrant init gentoo

此命令会在 /your/path/vagrant_name 目录下建立 Vagrantfile 基础配置文件,你可以通过 git 等方式来分享。下面在此目录下执行 vagrant box add xxx 去拉一个现成的镜像下来,鄙人还是习惯拉 Gentoo 的一个 vbox 镜像。当然下面例子中的 Gentoo 镜像存放在 dropbox 中,内地的网络环境 你懂得,故需要一些 你懂得 操作,这里不做介绍了。

$ vagrant box add gentoo https://dl.dropboxusercontent.com/s/xfl63k64zliixid/gentoo-20131029-i686.box
==> box: Adding box 'gentoo' (v0) for provider:
box: Downloading: https://dl.dropboxusercontent.com/s/xfl63k64zliixid/gentoo-20131029-i686.box
==> box: Successfully added box 'gentoo' (v0) for 'virtualbox'!

除了直接去网址下载,也可以直接下载 Vagrant Cloud 中的镜像

$ vagrant box add d11wtq/gentoo

具体需要什么镜像可以去如下网址:

二. 运行

镜像拉下来后,就可以启动了

$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'gentoo'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: vagrant_default_1410100872394_79587
==> 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: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Mounting shared folders...
    default: /vagrant => /Users/Havee/Documents/git/vagrant

嗯,你的虚拟机已经起来了,连接的话,直接 vagrant ssh 即可

$ vagrant ssh
vagrant@local ~ $ uname -a
Linux local 3.10.7-gentoo-r1 #1 SMP Wed Oct 30 20:15:42 UTC 2013 i686 Intel(R) Core(TM) i5-3470 CPU @ 3.20GHz GenuineIntel GNU/Linux

随后,你就可以随意的根据你的习惯,去部署你的一切。当然如果你觉得 vbox 笨重的话,docker 是一个非常好的解决方案。

三. 配置

Vagrantfile 文件就是基础配置文件下面列出一些常用的配置项

a. 基础设定
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
    config.vm.box = "gentoo"
    config.vm.box_check_update = false
    config.vm.network "forwarded_port", guest: 80, host: 8080   # 端口转发
    config.vm.network "private_network", ip: "192.168.33.10"    # 或 config.vm.network "public_network",顾名思义
    config.ssh.forward_agent = true
    config.vm.synced_folder "./", "/vagrant"
end

一目了然的配置,名称,更新,端口转发,网络,ssh 以及共享目录。

b. Provider

由于 VirtualBox 免费,且跨平台,安装方便,很多人都使用 VirtualBox。以 VirtualBox 为例:

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
    ......
    config.vm.provider "virtualbox" do |vb|
        vb.gui = true
        vb.name = "gentoo"
        vb.memory = 1024
        vb.cpus = 2
        vb.customize ["modifyvm", :id, "--cpuexecutioncap", "80"]
    end
    ......
end

以上配置也是一目了然,VMWare Fusion 呢

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
    ......
    config.vm.provider "vmware_fusion" do |vb|
        vb.gui = true
        vb.vmx["memsize"] = "1024"
        vb.vmx["numvcpus"] = "2"
    end
    ......
end

其他的虚拟机,请阅读文档: http://docs.vagrantup.com/v2/providers/index.html

c. 多机环境

尽管我觉得多个 box 运行一个环境,非常的奢侈,与其跑多个虚拟机,倒不如用 docker 来管理。但谁知道大家的 cpu, ram 是否叼炸天呢。各有所好嘛……

config.vm.define :app1 do |app1|
    app1.vm.box = "app1"
    app1.vm.network "private_network", ip: "192.168.33.10"
    app1.memory = 512
    app1.cpus = 2
    app1.vm.customize [ "modifyvm", :id, "--name", "app1", "--cpuexecutioncap", "50" ]
end
config.vm.define :app2 do |app2|
    app2.vm.box = "app2"
    app2.vm.network "private_network", ip: "192.168.33.11"
    app2.memory = 512
    app2.cpus = 1
    app1.vm.customize [ "modifyvm", :id, "--name", "app2", "--cpuexecutioncap", "40" ]
end
......

启动

$ vagrant up app1
$ vagrant up app2
d. 常用命令
$ vagrant init                  # 初始化
$ vagrant up                    # 启动
$ vagrant halt                  # 关闭
$ vagrant reload                # 重启
$ vagrant suspend
$ vagrant resume
$ vagrant ssh                   # ssh 连接到虚拟机
$ vagrant status                # 虚拟机状态
$ vagrant destroy
$ vagrant package               # 打包
$ vagrant box add name url      # 添加镜像
$ vagrant box list              # 列表
$ vagrant box remove name       # 移除镜像
$ vagrant box repackage         # 重新打包

四. 打包环境

万事俱备,公司内部要统一开发环境,打包出来让同事在统一环境下开发吧,以后不会出现 我机子上没这个问题呀 这种说不清道不明的状况了。

打包,当然是退出你的虚拟机后再操作的。

$ vagrant package
==> gentoo: Attempting graceful shutdown of VM...
==> gentoo: Clearing any previously set forwarded ports...
==> gentoo: Exporting VM...
==> gentoo: Compressing package to: /Users/Havee/Documents/git/vagrant/package.box

将 package.box 拿给同事吧,让他们加入该 box,你们的开发环境就完全一致了

$ vagrant box add gentoo /path/package.box

参考: https://docs.vagrantup.com/v2/