Vagrant 学习笔记

Vagrant 简介

  • Vagrant 是一个基于 Ruby 的工具,用于创建和部署虚拟化开发环境。Vagrant 易于配置的、可重复的,为团队提供一致的工作环境,解决环境隔离依赖等问题,最大限度地提高生产效率。
  • 开发人员只需要创建并配置 Vagrantfile,在通过 vagrant up 命令创建出所需的开发环境。也可以通过共享 Vagrantfile 文件,在任何其他机器上使用 Vagrant 构建相同的开发环境。

Vagrant 环境安装

Vagrant的运行,需要依赖某项具体的虚拟化技术,最常见的有以下几种:

  • virtualbox:
  • vmware:
  • libvirt:linux 上的虚拟技术
  • hyperv:win10 自带虚拟技术
  • docker:最流行最火的容器技术

1.安装前准备

打开任务管理器 -> 性能 -> CPU 查看虚拟化是否开启。

如果未开启,进入 bios 界面开启 CPU 虚拟化功能。

2.安装 virtualbox

本文选择virtualbox做示例

下载地址:https://www.virtualbox.org/wiki/Downloads

3.安装 vagrant

下载地址:https://www.vagrantup.com/downloads.html

Vagrant 基本命令

在 Vagrant 中,是通过把虚拟机打包成 box 来实现一致的、可重复的环境,基于同一个box,构建可以得到相同的环境。Vagrant 也分成两部分:一是 box 生命周期管理,二是虚拟机生命周期管理。

1.box 管理命令

PS C:\Users\wangjie> vagrant box help
Usage: vagrant box <subcommand> [<args>]

Available subcommands:
     add                        添加box到本地vagrant环境
     list                       列出本地环境中所有的box
     outdated                   检查并更新所有本地环境中的box
     prune                      清理本地环境中的box
     remove                     删除本地环境中指定的box
     repackage                  重新打包本地环境中指定的box
     update                     更新打包本地环境中指定的box

2.虚拟机管理命令

PS C:\Users\wangjie> vagrant -h
Usage: vagrant [options] <command> [<args>]

    -v, --version                    Print the version and exit.
    -h, --help                       Print this help.

Common commands:
     box             manages boxes: installation, removal, etc.
     cloud           manages everything related to Vagrant Cloud
     destroy         stops and deletes all traces of the vagrant machine
     global-status   outputs status Vagrant environments for this user
     halt            stops the vagrant machine
     help            shows the help for a subcommand
     init            initializes a new Vagrant environment by creating a Vagrantfile
     login
     package         packages a running vagrant environment into a box
     plugin          manages plugins: install, uninstall, update, etc.
     port            displays information about guest port mappings
     powershell      connects to machine via powershell remoting
     provision       provisions the vagrant machine
     push            deploys code in this environment to a configured destination
     rdp             connects to machine via RDP
     reload          restarts vagrant machine, loads new Vagrantfile configuration
     resume          resume a suspended vagrant machine
     snapshot        manages snapshots: saving, restoring, etc.
     ssh             connects to machine via SSH
     ssh-config      outputs OpenSSH valid configuration to connect to the machine
     status          outputs status of the vagrant machine
     suspend         suspends the machine
     up              starts and provisions the vagrant environment
     upload          upload to machine via communicator
     validate        validates the Vagrantfile
     version         prints current and latest Vagrant version
     winrm           executes commands on a machine via WinRM
     winrm-config    outputs WinRM configuration to connect to the machine

For help on any individual command run `vagrant COMMAND -h`

虚拟机管理命令通常在项目中 Vagrantfile 文件所在目录下运行,常用命令如下

vagrant init [box]          当前目录创建 Vagrantfile 文件,可以指定box
vagrant up [name]           通过 Vagrantfile 文件启动虚拟机
vagrant status [name]       查看虚拟机状态
vagrant ssh [name]          ssh登录虚拟机
vagrant suspend [name]      挂起虚拟机
vagrant resume [name]       恢复挂起的虚拟机
vagrant reload [name]       重启虚拟机,应用新 Vagrantfile 文件 
vagrant package [name]      把一个运行的虚拟机打包成 box
vagrant halt [name]         关闭虚拟机
vagrant destroy [name]      销毁虚拟机

Vagrantfile 文件配置

Vagrant 命令使用很简单,关键在于复杂的环境配置在 Vagrant 中怎么体现。从上面可以看出,Vagrant 对于虚拟机的管理全部依赖于 Vagrantfile 文件的配置。当运行任何vagrant命令时,Vagrant 从当前目录开始向上查找它可以找到的第一个 Vagrantfile。例如:

D:\Study\Easy_install\vagrant_demo\Vagrantfile
D:\Study\Easy_install\Vagrantfile
D:\Study\Vagrantfile
D:\Vagrantfile

下面来学习 Vagrantfile 文件的编写:

1.最简化配置

Vagrant.configure("2") do |config|
  config.vm.box = "centos/7"
end

这是通过 vagrant init centos/7 创建的最简单的 Vagrantfile。

  • Vagrant.configure("2") 代表当前支持版本 1.1+ 到 2.0.x
  • config.vm.box = "centos/7" 指定 box

启动后的虚拟机配置如下:

  • CPU:1核
  • 内存:512M
  • 网络:网络地址转换
  • 硬盘:40G

2.环境变量配置

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

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

3.虚拟机配置

  • 定义虚拟机
  config.vm.define "test" do |node|     # test Vagrant 识别的虚拟机名称
    node.vm.box = "centos/7"            # node Vagrantfile 识别的节点名称
    node.vm.hostname="vmtest"           # 虚拟机 hostname
  end
  • VirtualBox 配置
  node.vm.provider "virtualbox" do |vb|     # 使用 VirtualBox 提供虚拟化
    vb.name = "vbtest"                      # VirtualBox 识别的虚拟机名称
    vb.memory = 2048                        # 内存 2G
    vb.cpus = 2                             # CPU 2核
    vb.gui = true                           # 启动图形化界面
    vb.linked_clone = true                  # 链接克隆
  end
  • ssh 配置
  node.ssh.username = "wangjie"
  node.ssh.password = "123456"
  • 网络配置

端口转发: 网络地址转换

    node.vm.network "forwarded_port", guest: 80, host: 8080, auto_correct: true
    node.vm.usable_port_range = 8000..8999

私有网络: virtualbox__intnet 使用 virtualbox 内部网络

    # 使用 host-only 网络
    config.vm.network "private_network", ip: "192.168.99.14", name: "VirtualBox Host-Only Ethernet Adapter #2"
    # 使用内部网络
    config.vm.network "private_network", type: "dhcp", , virtualbox__intnet: true

公共网络: 桥接网卡

    config.vm.network "public_network"
    config.vm.network "public_network", use_dhcp_assigned_default_route: true
    config.vm.network "public_network", bridge: [
      "en1: Intel(R) Wireless-AC 9560",
      "en6: Realtek Gaming GBE Family Controller",
    ]
  • 共享目录

支持 type:nfs、rsync、smb

  # 第一个主机路径,可以是相对路径。第二个虚拟机路径,必须绝对路径
  node.vm.synced_folder "src/", "/srv/website"
  
  # 禁用同步
  node.vm.synced_folder "src/", "/srv/website", disabled: true
  node.vm.synced_folder ".", "/vagrant", disabled: true
  
  # 设置所属用户/组
  node.vm.synced_folder "src/", "/srv/website", owner: "root", group: "root"
  
  • provision 设置

文件上传

  # 文件上传
  node.vm.provision "file", type: "file", source: "~/.gitconfig", destination: ".gitconfig"
  # 目录上传,不加尾部斜杠
  node.vm.provision "file", source: "~/path/to/host/folder", destination: "$HOME/remote/newfolder"

shell 命令执行

  # 内联脚本
  node.vm.provision "bootstrap", type: "shell", inline: "echo Hello, World"
  # 脚本参数
  node.vm.provision "shell" do |s|
    s.inline = "echo $1"
    s.args   = ["hello, world!"]
  end
  
  # 脚本定义
$script = <<-SCRIPT
echo I am provisioning...
date > /etc/vagrant_provisioned_at
SCRIPT

  node.vm.provision "shell", inline: $script

  # 外部脚本
  node.vm.provision "shell", path: "script.sh"
  # 普通用户执行
  node.vm.provision "shell", privileged: false, path: "script.sh"
对于 provision 设置,在运行 vagrant up,vagrant provision和vagrant reload --provision 时可以应用 provision 配置。provision 默认只运行一次,可以设置标志 run: "always", 每次都运行。设置 run 为 never, 则运行 vagrant provision --provision-with [provision name]。

结尾

工作中经常用到虚拟机,总是来来回回折腾,虽然可以虚拟机克隆缩短时间,但是虚拟机里面的配置没有有效的办法保存。花点时间学习一下 Vagrant,将工作学习所需的虚拟机环境有效保存下来,避免重复劳动,也节约时间,让有限的时间花在有意义的事情上。

本文示例

# -*- mode: ruby -*-
# vi: set ft=ruby :

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

  config.vm.define "test" do |node|

    node.vm.box = "centos/7"
    node.vm.hostname="vmtest"
    
    node.vm.network "forwarded_port", guest: 80, host: 8080, auto_correct: true
    node.vm.usable_port_range = 8000..8999

    node.vm.network "private_network", ip: "192.168.99.150", name: "VirtualBox Host-Only Ethernet Adapter #2"

    node.vm.network "public_network"

    node.vm.provider "virtualbox" do |vb|
      vb.name = "vb_test"
      vb.memory = 2048
      vb.cpus = 2
      # vb.gui = true
      vb.linked_clone = true                          
    end

    node.vm.synced_folder "share", "/home/vagrant/share", disabled: true
    node.vm.synced_folder ".", "/vagrant", disabled: true

    node.vm.provision "file", source: "test.sh", destination: "/home/vagrant/test.sh", run: "always"

    node.vm.provision "shell", inline: "bash /home/vagrant/test.sh", run: "always"
    node.vm.provision "shell", path: "test.sh", run: "always"

  end
end

GitHub 地址:https://github.com/wj5633/Easy_install

posted @ 2019-07-21 20:25  兔头咖啡  阅读(446)  评论(0编辑  收藏  举报


作者:兔头咖啡
出处:http://www.cnblogs.com/wj5633/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。