vagrant使用

ReadMe
vagrant使用步骤:
1、mkdir -p prj ; vagrant init
创建Vagrantfile
2、vagrant box add ubuntu/trusty64
下载ubuntu/trusty64镜像 或 自行指定本地的box

移除box:
vagrant box remove

在Vagrantfile中指定使用的box:
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/trusty64"
end

指定使用的vm版本:
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/trusty64"
config.vm.box_version = "1.1.0"
end

指定box的url:
Vagrant.configure("2") do |config|
config.vm.box = "hashicorp/precise64"
config.vm.box_url = "http://files.vagrantup.com/precise64.box"
end


3、启动vm:
vagrant up
ssh连接vm:
vagrant ssh

4、同步文件夹(synced folder)
默认情况下,vm project所在的文件夹和/vagrant是同步的
ssh时所在的目录是/home/vagrant,/home/vagrant和/vagrant是不一样的
config.vm.synced_folder
Vagrant.configure("2") do |config|
# other config here


config.vm.synced_folder "src/", "/srv/website"
end
The first parameter is a path to a directory on the host machine. If the path is relative, it is relative to the project root. The second parameter must be an absolute path of where to share the folder within the guest machine. This folder will be created (recursively, if it must) if it does not exist.
第一个参数如果是相对路径,是相对于项目根的文件夹,第二个路径是客户机上的绝对路径,若无则自动创建
其他选项:
create (boolean) - If true, the host path will be created if it does not exist. Defaults to false.

disabled (boolean) - If true, this synced folder will be disabled and will not be setup. This can be used to disable a previously defined synced folder or to conditionally disable a definition based on some external factor.

group (string) - The group that will own the synced folder. By default this will be the SSH user. Some synced folder types do not support modifying the group.

mount_options (array) - A list of additional mount options to pass to the mount command.

owner (string) - The user who should be the owner of this synced folder. By default this will be the SSH user. Some synced folder types do not support modifying the owner.

type (string) - The type of synced folder. If this is not specified, Vagrant will automatically choose the best synced folder option for your environment. Otherwise, you can specify a specific type such as "nfs".

id (string) - The name for the mount point of this synced folder in the guest machine. This shows up when you run mount in the guest machine.

5、服务开通(PROVISIONING)
Vagrant内置支持部分服务自动开通(即在执行vagrant up时自动执行某些脚本)
ex:ubuntu下自动安装apache
Create the following shell script and save it as bootstrap.sh in the same directory as your Vagrantfile
#!/usr/bin/env bash

apt-get update
apt-get install -y apache2
if ! [ -L /var/www ]; then
rm -rf /var/www
ln -fs /vagrant /var/www
fi

然后在Vagrantfile中配置执行该脚本文件:

Vagrant.configure("2") do |config|
config.vm.box = "hashicorp/precise64"
config.vm.provision :shell, path: "bootstrap.sh"
end


After everything is configured, just run vagrant up to create your machine and Vagrant will automatically provision it. You should see the output from the shell script appear in your terminal. If the guest machine is already running from a previous step, run vagrant reload --provision, which will quickly restart your virtual machine, skipping the initial import step. The provision flag on the reload command instructs Vagrant to run the provisioners, since usually Vagrant will only do this on the first vagrant up

6、创建自己的基础box(base box):
vagrant package --base my-virtual-machine

7、网络(Networking):
端口转发(Port Forwarding)
Port forwarding allows you to specify ports on the guest machine to share via a port on the host machine. This allows you to access a port on your own machine, but actually have all the network traffic forwarded to a specific port on the guest machine

Let us setup a forwarded port so we can access Apache in our guest. Doing so is a simple edit to the Vagrantfile, which now looks like this:


Vagrant.configure("2") do |config|
config.vm.box = "hashicorp/precise64"
config.vm.provision :shell, path: "bootstrap.sh"
config.vm.network :forwarded_port, guest: 80, host: 4567
end

Run a vagrant reload or vagrant up (depending on if the machine is already running) so that these changes can take effect.

Once the machine is running again, load http://127.0.0.1:4567 in your browser. You should see a web page that is being served from the virtual machine that was automatically setup by Vagrant.

8、Vagrant共享(Share):
Vagrant Share lets you share your Vagrant environment to anyone around the world with an Internet connection. It will give you a URL that will route directly to your Vagrant environment from any device in the world that is connected to the Internet
首先需要在Atlas注册,
然后执行:vagrant login
$ vagrant login
Username or Email: mitchellh
Password (will be hidden):
You are now logged in!

登录成功后,执行:vagrant share
$ vagrant share
...
==> default: Your Vagrant Share is running!
==> default: URL: http://XXX-YYY-ZZZ.vagrantshare.com
...

停止分享的话,Ctrl+C即可

9、Teardown
挂起:vagrant suspend
the virtual machine by calling vagrant suspend will save the current running state of the machine and stop it. When you are ready to begin working again, just run vagrant up, and it will be resumed from where you left off. The main benefit of this method is that it is super fast, usually taking only 5 to 10 seconds to stop and start your work. The downside is that the virtual machine still eats up your disk space, and requires even more disk space to store all the state of the virtual machine RAM on disk

关机:vagrant halt
the virtual machine by calling vagrant halt will gracefully shut down the guest operating system and power down the guest machine. You can use vagrant up when you are ready to boot it again. The benefit of this method is that it will cleanly shut down your machine, preserving the contents of disk, and allowing it to be cleanly started again. The downside is that it'll take some extra time to start from a cold boot, and the guest machine still consumes disk space

摧毁:vagrant destroy
the virtual machine by calling vagrant destroy will remove all traces of the guest machine from your system. It'll stop the guest machine, power it down, and remove all of the guest hard disks. Again, when you are ready to work again, just issue a vagrant up. The benefit of this is that no cruft is left on your machine. The disk space and RAM consumed by the guest machine is reclaimed and your host machine is left clean. The downside is that vagrant up to get working again will take some extra time since it has to reimport the machine and re-provision it

10、Vagrantfile
Link
定义多个机器:
Multiple machines are defined within the same project Vagrantfile using the config.vm.define method call. This configuration directive is a little funny, because it creates a Vagrant configuration within a configuration. An example shows this best:

Vagrant.configure("2") do |config|
config.vm.provision "shell", inline: "echo Hello"


config.vm.define "web" do |web|
web.vm.box = "apache"
end

config.vm.define "db" do |db|
db.vm.box = "mysql"
end
end
As you can see, config.vm.define takes a block with another variable. This variable, such as web above, is the exact same as the config variable, except any configuration of the inner variable applies only to the machine being defined. Therefore, any configuration on web will only affect the web machine

CONFIGURATION VERSION:
you run vagrant init today, the Vagrantfile will be in roughly the following format:

Vagrant.configure("2") do |config|
# ...
end
The "2" in the first line above represents the version of the configuration object config that will be used for configuration for that block (the section between the do and the end). This object can be very different from version to version

LOOP OVER VM DEFINITIONS:循环定义VM
(1..3).each do |i|
config.vm.define "node-#{i}" do |node|
node.vm.provision "shell",
inline: "echo hello from node #{i}"
end
end


OVERWRITE HOST LOCALE IN SSH SESSION:

Usually, host locale environment variables are passed to guest. It may cause failures if the guest software do not support host locale. One possible solution is override locale in the Vagrantfile:

ENV["LC_ALL"] = "en_US.UTF-8"


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

The change is only visible within the Vagrantfile.

MACHINE SETTINGS:
config.vm

Config namespace: config.vm

The settings within config.vm modify the configuration of the machine that Vagrant manages.

AVAILABLE SETTINGS


config.vm.boot_timeout - The time in seconds that Vagrant will wait for the machine to boot and be accessible. By default this is 300 seconds.




config.vm.box - This configures what box the machine will be brought up against. The value here should be the name of an installed box or a shorthand name of a box in HashiCorp's Atlas.

This option requires Vagrant 1.5 or higher. You can download the latest version of Vagrant from the Vagrant installers page.




config.vm.box_check_update - If true, Vagrant will check for updates to the configured box on every vagrant up. If an update is found, Vagrant will tell the user. By default this is true. Updates will only be checked for boxes that properly support updates (boxes from HashiCorp's Atlas or some other versioned box).




config.vm.box_download_checksum - The checksum of the box specified by config.vm.box_url. If not specified, no checksum comparison will be done. If specified, Vagrant will compare the checksum of the downloaded box to this value and error if they do not match. Checksum checking is only done when Vagrant must download the box.

If this is specified, then config.vm.box_download_checksum_type must also be specified.




config.vm.box_download_checksum_type - The type of checksum specified by config.vm.box_download_checksum (if any). Supported values are currently "md5", "sha1", and "sha256".




config.vm.box_download_client_cert - Path to a client certificate to use when downloading the box, if it is necessary. By default, no client certificate is used to download the box.




config.vm.box_download_ca_cert - Path to a CA cert bundle to use when downloading a box directly. By default, Vagrant will use the Mozilla CA cert bundle.




config.vm.box_download_ca_path - Path to a directory containing CA certificates for downloading a box directly. By default, Vagrant will use the Mozilla CA cert bundle.




config.vm.box_download_insecure - If true, then SSL certificates from the server will not be verified. By default, if the URL is an HTTPS URL, then SSL certs will be verified.




config.vm.box_download_location_trusted - If true, then all HTTP redirects will be treated as trusted. That means credentials used for initial URL will be used for all subsequent redirects. By default, redirect locations are untrusted so credentials (if specified) used only for initial HTTP request.




config.vm.box_url - The URL that the configured box can be found at. If config.vm.box is a shorthand to a box in HashiCorp's Atlas then this value does not need to be specified. Otherwise, it should point to the proper place where the box can be found if it is not installed.

This can also be an array of multiple URLs. The URLs will be tried in order. Note that any client certificates, insecure download settings, and so on will apply to all URLs in this list.

The URLs can also be local files by using the file:// scheme. For example: "file:///tmp/test.box".




config.vm.box_version - The version of the box to use. This defaults to ">= 0" (the latest version available). This can contain an arbitrary list of constraints, separated by commas, such as: >= 1.0, < 1.5. When constraints are given, Vagrant will use the latest available box satisfying these constraints.




config.vm.communicator - The communicator type to use to connect to the guest box. By default this is "ssh", but should be changed to "winrm" for Windows guests.




config.vm.graceful_halt_timeout - The time in seconds that Vagrant will wait for the machine to gracefully halt when vagrant halt is called. Defaults to 60 seconds.




config.vm.guest - The guest OS that will be running within this machine. This defaults to :linux, and Vagrant will auto-detect the proper distro. Vagrant needs to know this information to perform some guest OS-specific things such as mounting folders and configuring networks.




config.vm.hostname - The hostname the machine should have. Defaults to nil. If nil, Vagrant will not manage the hostname. If set to a string, the hostname will be set on boot.




config.vm.network - Configures networks on the machine. Please see the networking page for more information.




config.vm.post_up_message - A message to show after vagrant up. This will be shown to the user and is useful for containing instructions such as how to access various components of the development environment.




config.vm.provider - Configures provider-specific configuration, which is used to modify settings which are specific to a certain provider. If the provider you are configuring does not exist or is not setup on the system of the person who runs vagrant up, Vagrant will ignore this configuration block. This allows a Vagrantfile that is configured for many providers to be shared among a group of people who may not have all the same providers installed.




config.vm.provision - Configures provisioners on the machine, so that software can be automatically installed and configured when the machine is created. Please see the page on provisioners for more information on how this setting works.




config.vm.synced_folder - Configures synced folders on the machine, so that folders on your host machine can be synced to and from the guest machine. Please see the page on synced folders for more information on how this setting works.




config.vm.usable_port_range - A range of ports Vagrant can use for handling port collisions and such. Defaults to 2200..2250.

SSH SETTINGS

onfig namespace: config.ssh

The settings within config.ssh relate to configuring how Vagrant will access your machine over SSH. As with most Vagrant settings, the defaults are typically fine, but you can fine tune whatever you would like.

AVAILABLE SETTINGS


config.ssh.username - This sets the username that Vagrant will SSH as by default. Providers are free to override this if they detect a more appropriate user. By default this is "vagrant," since that is what most public boxes are made as.




config.ssh.password - This sets a password that Vagrant will use to authenticate the SSH user. Note that Vagrant recommends you use key-based authentication rather than a password (see private_key_path) below. If you use a password, Vagrant will automatically insert a keypair ifinsert_key is true.




config.ssh.host - The hostname or IP to SSH into. By default this is empty, because the provider usually figures this out for you.




config.ssh.port - The port to SSH into. By default this is port 22.




config.ssh.guest_port - The port on the guest that SSH is running on. This is used by some providers to detect forwarded ports for SSH. For example, if this is set to 22 (the default), and Vagrant detects a forwarded port to port 22 on the guest from port 4567 on the host, Vagrant will attempt to use port 4567 to talk to the guest if there is no other option.




config.ssh.private_key_path - The path to the private key to use to SSH into the guest machine. By default this is the insecure private key that ships with Vagrant, since that is what public boxes use. If you make your own custom box with a custom SSH key, this should point to that private key.

You can also specify multiple private keys by setting this to be an array. This is useful, for example, if you use the default private key to bootstrap the machine, but replace it with perhaps a more secure key later.




config.ssh.keys_only - Only use Vagrant-provided SSH private keys (do not use any keys stored in ssh-agent). The default value is true.`




config.ssh.paranoid - Perform strict host-key verification. The default value is false.




config.ssh.forward_agent - If true, agent forwarding over SSH connections is enabled. Defaults to false.




config.ssh.forward_x11 - If true, X11 forwarding over SSH connections is enabled. Defaults to false.




config.ssh.forward_env - An array of host environment variables to forward to the guest. If you are familiar with OpenSSH, this corresponds to the SendEnv parameter.
config.ssh.forward_env = ["CUSTOM_VAR"]





config.ssh.insert_key - If true, Vagrant will automatically insert a keypair to use for SSH, replacing Vagrant's default insecure key inside the machine if detected. By default, this is true.

This only has an effect if you do not already use private keys for authentication or if you are relying on the default insecure key. If you do not have to care about security in your project and want to keep using the default insecure key, set this to false.




config.ssh.proxy_command - A command-line command to execute that receives the data to send to SSH on stdin. This can be used to proxy the SSH connection. %h in the command is replaced with the host and %p is replaced with the port.




config.ssh.pty - If true, pty will be used for provisioning. Defaults to false.

This setting is an advanced feature that should not be enabled unless absolutely necessary. It breaks some other features of Vagrant, and is really only exposed for cases where it is absolutely necessary. If you can find a way to not use a pty, that is recommended instead.




config.ssh.shell - The shell to use when executing SSH commands from Vagrant. By default this is bash -l. Note that this has no effect on the shell you get when you run vagrant ssh. This configuration option only affects the shell to use when executing commands internally in Vagrant.




config.ssh.export_command_template - The template used to generate exported environment variables in the active session. This can be useful when using a Bourne incompatible shell like C shell. The template supports two variables which are replaced with the desired environment variable key and environment variable value: %ENV_KEY% and %ENV_VALUE%. The default template is:
config.ssh.export_command_template = 'export %ENV_KEY%="%ENV_VALUE%"'

config.ssh.sudo_command - The command to use when executing a command with sudo. This defaults to sudo -E -H %c. The %c will be replaced by the command that is being executed.

11、Vagrant环境变量
Link
Vagrant has a set of environmental variables that can be used to configure and control it in a global way. This page lists those environmental variables.

VAGRANT_DEBUG_LAUNCHER

For performance reasons, especially for Windows users, Vagrant uses a static binary to launch the actual Vagrant process. If you have very early issues when launching Vagrant from the official installer, you can specify the VAGRANT_DEBUG_LAUNCHER environment variable to output debugging information about the launch process.

VAGRANT_DEFAULT_PROVIDER

This configures the default provider Vagrant will use.

This normally does not need to be set since Vagrant is fairly intelligent about how to detect the default provider. By setting this, you will force Vagrant to use this provider for any new Vagrant environments. Existing Vagrant environments will continue to use the provider they came up with. Once you vagrant destroy existing environments, this will take effect.

VAGRANT_BOX_UPDATE_CHECK_DISABLE

By default, Vagrant will query the metadata API server to see if a newer box version is available for download. This optional can be disabled on a per-Vagrantfile basis with config.vm.box_check_update, but it can also be disabled globally setting VAGRANT_BOX_UPDATE_CHECK_DISABLE to any non-empty value.

This option will not affect global box functions like vagrant box update.

VAGRANT_CHECKPOINT_DISABLE

Vagrant does occasional network calls to check whether the version of Vagrant that is running locally is up to date. We understand that software making remote calls over the internet for any reason can be undesirable. To surpress these calls, set the environment variable VAGRANT_CHECKPOINT_DISABLE to any non-empty value.

If you use other HashiCorp tools like Packer and would prefer to configure this setting only once, you can set CHECKPOINT_DISABLE instead.

VAGRANT_CWD

VAGRANT_CWD can be set to change the working directory of Vagrant. By default, Vagrant uses the current directory you are in. The working directory is important because it is where Vagrant looks for the Vagrantfile. It also defines how relative paths in the Vagrantfile are expanded, since they're expanded relative to where the Vagrantfile is found.

This environmental variable is most commonly set when running Vagrant from a scripting environment in order to set the directory that Vagrant sees.

VAGRANT_DOTFILE_PATH

VAGRANT_DOTFILE_PATH can be set to change the directory where Vagrant stores VM-specific state, such as the VirtualBox VM UUID. By default, this is set to .vagrant. If you keep your Vagrantfile in a Dropbox folder in order to share the folder between your desktop and laptop (for example), Vagrant will overwrite the files in this directory with the details of the VM on the most recently-used host. To avoid this, you could set VAGRANT_DOTFILE_PATH to .vagrant-laptop and .vagrant-desktop on the respective machines. (Remember to update your .gitignore!)

VAGRANT_HOME

VAGRANT_HOME can be set to change the directory where Vagrant stores global state. By default, this is set to ~/.vagrant.d. The Vagrant home directory is where things such as boxes are stored, so it can actually become quite large on disk.

VAGRANT_LOG

VAGRANT_LOG specifies the verbosity of log messages from Vagrant. By default, Vagrant does not actively show any log messages.

Log messages are very useful when troubleshooting issues, reporting bugs, or getting support. At the most verbose level, Vagrant outputs basically everything it is doing.

Available log levels are "debug," "info," "warn," and "error." Both "warn" and "error" are practically useless since there are very few cases of these, and Vagrant generally reports them within the normal output.

"info" is a good level to start with if you are having problems, because while it is much louder than normal output, it is still very human-readable and can help identify certain issues.

"debug" output is extremely verbose and can be difficult to read without some knowledge of Vagrant internals. It is the best output to attach to a support request or bug report, however.

VAGRANT_NO_COLOR

If this is set to any value, then Vagrant will not use any colorized output. This is useful if you are logging the output to a file or on a system that does not support colors.

The equivalent behavior can be achieved by using the --no-color flag on a command-by-command basis. This environmental variable is useful for setting this flag globally.

VAGRANT_FORCE_COLOR

If this is set to any value, then Vagrant will force colored output, even if it detected that there is no TTY or the current environment does not support it.

The equivalent behavior can be achieved by using the --color flag on a command-by-command basis. This environmental variable is useful for setting this flag globally.

VAGRANT_NO_PLUGINS

If this is set to any value, then Vagrant will not load any 3rd party plugins. This is useful if you install a plugin and it is introducing instability to Vagrant, or if you want a specific Vagrant environment to not load plugins.

Note that any vagrant plugin commands automatically do not load any plugins, so if you do install any unstable plugins, you can always use the vagrant plugin commands without having to worry.

VAGRANT_NO_PARALLEL

If this is set, Vagrant will not perform any parallel operations (such as parallel box provisioning). All operations will be performed in serial.

VAGRANT_SKIP_SUBPROCESS_JAILBREAK

As of Vagrant 1.7.3, Vagrant tries to intelligently detect if it is running in the installer or running via Bundler. Although not officially supported, Vagrant tries its best to work when executed via Bundler. When Vagrant detects that you have spawned a subprocess that lives outside of Vagrant's installer, Vagrant will do its best to reset the preserved environment dring the subprocess execution.

If Vagrant detects it is running outside of the officially installer, the original environment will always be restored. You can disable this automatic jailbreak by setting VAGRANT_SKIP_SUBPROCESS_JAILBREAK.

VAGRANT_VAGRANTFILE

This specifies the filename of the Vagrantfile that Vagrant searches for. By default, this is "Vagrantfile." Note that this is not a file path, but just a filename.

This environmental variable is commonly used in scripting environments where a single folder may contain multiple Vagrantfiles representing different configurations.

12、
命令行

问题:
1. 虚拟机软件问题

我使用的是 开源虚拟机软件 VirtualBox。在安装完Virtualbox后, vagrant竟然没有识别出 VirtualBox,直接从官网龟速下载VirtualBox,受不了啊!!!在尝试设置PATH无效后,Google找到:

”sets the VBOX_INSTALL_PATH or VBOX_MSI_INSTALL_PATH environment variable which is what Vagrant uses to look it up“,直接设置VBOX_INSTALL_PATH后,终于识别出默认的Virtualbox了。


vagrant下载的vbox默认位于$HOME下,请设置环境变量 : $VAGRANT_HOME


2. hashicorp/precise64

这个版本是hashicorp官方推荐的Box,但是下载完成后自己发现,竟然没有Vim以及其他很多常用软件。于是,自己使用的是Centos官方推荐的centos/6 Box。


3. 网络设置:端口转发

官网写的配置十分简单,只需要配置Vagrantfile后,调用 vagrant reload即可。但是自己在使用过程中出现了: Virtualbox Guest Additions Version不匹配的问题,导致端口转发配置无法生效。错误截图如下:



 网上找到的有两种方法没有解决这个问题:


1. 运行 vboxguest -5.1.8 setup

2. 重新编译vboxguest

另外一种方法是使用Centos GUI界面,运行vboxguest,自己没有尝试。解决这个问题的方法是使用:vagrant plugin install vagrant-vbguest (老外写的一个Vagrant插件,专门解决不匹配问题),在花费多个小时后,终于完成端口转发配置! 截个图庆祝下:



总结及困扰



Vagrant确实是一个好的工具,但是在把它使用好,需要投入一定的时间研究。在使用过程中,自己发现Vagrant的Box阉割的比较厉害,好处是Box占用磁盘空间小了很多,坏处就是以后使用某个软件的时候,需要花费时间填坑。

1.vagrant up无反应:
如果执行vagrant up之后,无任何反应,有可能是vagrant没有找到virtualbox,需要用姜virtualbox的路径放到环境变量PATH之中

3、同步文件夹问题:
the guest additions on this vm do not match the installed version of virtualbox
使用如下命令:
vagrant plugin install vagrant-vbguest

#Vagrant环境变量
VAGRANT_HOME: Boxes下载位置
VBOX_INSTALL_PATH 和 VBOX_MSI_INSTALL_PATH: VirtualBox安装路径


VAGRANT_HOME=d:/vbox
VBOX_INSTALL_PATH=D:\VirtualBox
VBOX_MSI_INSTALL_PATH=D:\VirtualBox
附,参考资料:


2.  http://www.vagrantbox.es/ 【镜像列表】