tigh 发表于 2015-11-26 10:23:20

Vagrant学习之提高篇(三)

1.Vagrantfile配置
1.1配置版本号Vagrant.configure(2) do |config|
# ...
end其中的“2”代表vagrant支持的配置版本。目前vagrant支持“1”和“2”两种配置版本Vagrant 1.0.x使用“1”

Vagrant 1.1以上,使用“2”
1.2 vagrant版本号
Vagrant.require_version ">= 1.3.5"
vagrant当前版本号大于1.3.5才能使用该项目
Vagrant.require_version &quot;>= 1.3.5&quot;, &quot;< 1.4.0&quot;


1.3循环
当我们创建多个虚拟机时,会用到循环
(1..3).each do |i|
config.vm.define &quot;node-#{i}&quot; do |node|
node.vm.provision &quot;shell&quot;,
inline: &quot;echo hello from node #{i}&quot;
end
end
注意,不能使用for循环


1.4 配置项
config.vm

config.ssh


config.winrm


config.vagrant



https://docs.vagrantup.com/v2/vagrantfile/machine_settings.html



2.BOX配置
box是vagrant环境文件
官方提供了很多box,可以直接使用: https://atlas.hashicorp.com/boxes/search
以下命令可以获取官方提供的box
$ vagrant box add USER/BOX
例如:vagrant box add hashicorp/precise64
也可以:vagrant
init hashicorp/precise64



2.1
BOX版本控制
2.1.1
vagrant box list
列出所有已经安装好的box
images


查看有哪些可用的box,需要登录box网站查看 https://atlas.hashicorp.com/USER/BOX
例如:https://atlas.hashicorp.com/hashicorp/precise64



2.1.2
box的更新



查看过期的box: vagrant
box outdated
更新: vagrant
box outdated

此命令只是更新box镜像,不会对正在运行的vm产生影响。如果要使用新box镜像,需要把vm destroy,然后在重新vagrant up



2.1.3
box的版本控制
config.vm.box_version选项控制box文件的版本


config.vm.box_check_update默认是enabled,vm每次up,重启,恢复都会检测box版本信息








3.使用vagrant自动部署



3.1文件file
Provisioner
name: &quot;file&quot;


具有两个参数:

source 将要上传的文件路径

destination 传到vm的路径


用户可以将文件从host,copy到vm
例如:

Vagrant.configure(&quot;2&quot;) do |config|
# ... other configuration
config.vm.provision &quot;file&quot;, source: &quot;~/.gitconfig&quot;, destination: &quot;.gitconfig&quot;
end
注意,此文件不会自动保持同步




3.2脚本部署



Provisioner
name: &quot;shell&quot;


https://docs.vagrantup.com/v2/provisioning/shell.html




3.2.1 脚本读入方式
inline
直接将脚本文件写入到Vagrantfile里面
$script = <<SCRIPT
echo I am provisioning...
date > /etc/vagrant_provisioned_at
SCRIPT
Vagrant.configure(&quot;2&quot;) do |config|
config.vm.provision &quot;shell&quot;, inline: $script
end
也可以从指定path读入脚本




Vagrant.configure(&quot;2&quot;) do |config|
config.vm.provision &quot;shell&quot;, path: &quot;script.sh&quot;
end
甚至可以从网络路径读入脚本:

Vagrant.configure(&quot;2&quot;) do |config|
config.vm.provision &quot;shell&quot;, path: &quot;https://example.com/provisioner.sh&quot;
end


3.2.2脚本参数传入

Vagrant.configure(&quot;2&quot;) do |config|
config.vm.provision &quot;shell&quot; do |s|
s.inline = &quot;echo $1&quot;
s.args   = &quot;'hello, world!'&quot;
end
end











3.3
ansible部署
Provisioner
name: &quot;ansible&quot;


https://docs.vagrantup.com/v2/provisioning/ansible.html






3.4 Puppet部署
Provisioner name: puppet


https://docs.vagrantup.com/v2/provisioning/puppet_apply.html


Provisioner name: puppet_server

https://docs.vagrantup.com/v2/provisioning/puppet_agent.html
页: [1]
查看完整版本: Vagrant学习之提高篇(三)