之前研究了Vagrant的使用 Try to use Vagrant on CentOS7,也簡單實現了在單份配置文件中配置多個虛擬機,但使用的box是從官網box頁面下載的。想使用Vagrant獨立製作一個屬於自己的box,故而有了這一篇文章。參考文檔在文末References部分列出。

Prerequisites

  • 網路環境正常,能訪問互聯網
  • 安裝 VagrantVirtualBox
  • CentOS系統鏡像,此處使用CentOS-7-x86_64-Minimal-1511.iso
  • 耐心、信心、恆心

Official Suggestions

以下是官方文檔給出的建議

About VirtualBox

VirtualBox中創建虛擬機,設置 * Disk Space: 磁盤空間選擇 動態分配 (個人定義80G) * Memory: 不要設置過高,512MB 即可 * Peripherals: 外設儘可能禁用,如AudioUSB等 * Newwork: 第一塊網卡必須設置爲NAT模式 (個人第二塊網卡設置Bridge橋接模式)

About Virtual OS

操作系統安裝完成後的配置

  • root用戶密碼: vagrant
  • 創建用戶: vagrant,密碼: vagrant
  • 用戶vagrant擁有 sudo 權限,可無密碼使用sudo
  • insecure keypair寫入到用戶vagrant家目錄~/.ssh/authorized_keys文件中,設置目錄.ssh權限0700,設置文件authorized_keys權限0600
  • SSH設置,在文件/etc/ssh/sshd_config 中設置 UseDNS no
  • 安裝VirtualBox Guest Additions (安裝依賴kernel-headerskernel-develbzip2gcc)

About Vagrant

如何使用Vagrant對創建好的虛擬機進行打包,製作box

使用vagrant package進行打包,語法格式

vagrant package --base BASENAME --output OUTPUTNAME
  • BASENAME是指virtualbox中的VM名稱,可通過命令vboxmanage list vms獲取
    • "CentOS7.1 Minimal" {0418a7c3-43bd-48ac-9574-13a4649dad45},雙引號中的即VM名稱
  • OUTPUTNAME生成的box的保存路徑,文件後綴設置成 .box

Operation Process

以下是操作過程,包含報錯及解決方案

VirtualBox Operation

  • 打開VirtualBox
  • 點擊New新建虛擬機
  • Memory size設置爲512MB
  • Hard Disk中選擇create a virtual hard disk now
  • Hard disk file type選擇VDI即可
  • Storage on physical hard disk選擇Dynamically allocated (動態分配)
  • File location and size按需設置,個人設置爲80G

創建完成後,選中新創建地虛擬機,點擊Setting,在新打開地窗口中,點擊左側選項卡進行設置 * System: 在MotherboardBoot Order中,取消勾選Floppy,使用右側箭頭調整Optical爲第一啓動順序 * Storage: 點擊Controller: IDE下方地Empty,點擊右側新出現的Optical Drive的光盤形狀按鈕,找到存放系統鏡像文件的路徑,載入系統安裝鏡像,此處使用的是CentOS-7-x86_64-Minimal-1511.iso * Audio: 取消勾選Enable Addio * Network: 在Adapter1中勾選Enable Network Adapter,將Attached to設置爲NAT;在Adapter2中勾選Enable Network Adapter,將Attached to設置爲Bridged Adapter(橋接模式) * USB: 取消勾選Enable USB Controller

點擊右下側OK按鈕完成設置操作

選中新創建地虛擬機,點擊Start,開始安裝系統

過程不詳細描述,個人分區方案 * /boot: 獨立分區,大小1G * swap: 大小2G * /: 55G 剩餘空間未分配,留作以後按需使用,如配置LVM

創建用戶可在安裝過程中操作,也可之後使用useradd命令手動創建

OS Operation

Yum Repo

備份目錄/etc/yum.repos.d/中的repo文件,使用163yum源 CentOS镜像使用帮助,安裝epel源。

cd /etc/yum.repos.d/

sudo mkdir -p bak

sudo mv ./*.repo bak

sudo curl -s http://mirrors.163.com/.help/CentOS7-Base-163.repo -o CentOS7-Base.repo

yum clean all

yum install -y epel-release

OS Update

此處操作可選,但個人建議進行

repo安裝完成後,執行系統更新

sudo yum -y update

內核也會更新,更新完成後,重啓系統,默認載入新版本內核,執行如下命令移除舊內核

#查看當前內核版本信息
uname -r

#查看已安裝的內核
rpm -qa | grep kernel

#移除舊內核,OLD_KERNEL即上一條命令結果中未使用地內核,直接複製即可
sudo yum remove OLD_KERNEL

User Management

  • root用戶密碼設置爲vagrant
  • 創建用戶vagrant,密碼爲vagrant
  • 使用visudo命令編輯/etc/sudoers
    • 添加vagrant ALL=(ALL) NOPASSWD: ALL,無密碼使用sudo
    • 註釋含requiretty的行
  • insecure keypair寫入到用戶vagrant家目錄~/.ssh/authorized_keys文件中(須手動創建該目錄),設置目錄.ssh權限0700,設置文件authorized_keys權限0600,可使用curl命令下載該文件(CentOS6.x|7.x Minimal中默認安裝了curl)

Other Setting

  • 修改SSH配置文件/etc/ssh/sshd_config 設置 UseDNS no
  • 安裝VirtualBox Guest Additions (安裝依賴kernel-headerskernel-develbzip2gcc) sh sudo yum install -y kernel-headers kernel-devel bzip2 gcc

Installing VirtualBox Guest Additions

以下操作過程並未預先安裝bzip2gcc,列出具體報錯信息

啓動VirtualBox中的指定虛擬機系統後,點擊窗口上側Device,選擇Insert Guest Additions CD image...

登入系統,以下操作以root用戶身份進行

  • 掛載Guest Additions CD image
[root@localhost ~]# cd /media/
[root@localhost media]# ls
[root@localhost media]# mkdir -pv /media/cdrom
mkdir: created directory ‘/media/cdrom’
[root@localhost media]# mount /dev/cdrom /media/cdrom
mount: /dev/sr0 is write-protected, mounting read-only
[root@localhost media]# cd /media/cdrom
  • 運行VBoxLinuxAdditions.run

    [root@localhost cdrom]# sh VBoxLinuxAdditions.run
    Verifying archive integrity... All good.
    Uncompressing VirtualBox 5.0.16 Guest Additions for Linux............
    VirtualBox Guest Additions installer
    Copying additional installer modules ...
    ./install.sh: line 345: bzip2: command not found
    tar: This does not look like a tar archive
    tar: Exiting with failure status due to previous errors
    ./install.sh: line 358: bzip2: command not found
    tar: This does not look like a tar archive
    tar: Exiting with failure status due to previous errors
    [root@localhost cdrom]#
    

    報錯,提示bzip2命令找不到,使用yum install -y bzip2安裝bzip2

  • 再次執行sh VBoxLinuxAdditions.run

Building the VirtualBox Guest Additions kernel modules
The gcc utility was not found. If the following module compilation fails then
this could be the reason and you should try installing it.

Building the main Guest Additions module[FAILED]
(Look at /var/log/vboxadd-install.log to find out what went wrong)
Doing non-kernel setup of the Guest Additions[  OK  ]
Installing the Window System drivers
Could not find the X.Org or XFree86 Window System, skipping.

報錯提示The gcc utility was not found.,使用yum install -y gcc安裝gcc

  • 再次執行sh VBoxLinuxAdditions.run
[root@localhost cdrom]# sh VBoxLinuxAdditions.run
Verifying archive integrity... All good.
Uncompressing VirtualBox 5.0.16 Guest Additions for Linux............
VirtualBox Guest Additions installer
Removing installed version 5.0.16 of VirtualBox Guest Additions...
Removing existing VirtualBox non-DKMS kernel modules[  OK  ]
Copying additional installer modules ...
Installing additional modules ...
Removing existing VirtualBox non-DKMS kernel modules[  OK  ]
Building the VirtualBox Guest Additions kernel modules
Building the main Guest Additions module[  OK  ]
Building the shared folder support module[  OK  ]
Building the OpenGL support module[  OK  ]
Doing non-kernel setup of the Guest Additions[  OK  ]
Starting the VirtualBox Guest Additions [  OK  ]
Installing the Window System drivers
Could not find the X.Org or XFree86 Window System, skipping.
[root@localhost cdrom]#

安裝成功

操作完成後,執行如下命令關閉系統

shutdown -h now

Vagrant Operation

使用Vagrant開始打包操作

執行如下命令,獲取目標虛擬機的VM名稱

vboxmanage list vms

此處爲"CentOS7.1 Minimal" {0418a7c3-43bd-48ac-9574-13a4649dad45}

Vagrant Package

打包過程耗時較長,需耐心等待

#獲取VM名稱
[flying@lemp ~]$ vboxmanage list vms | grep "CentOS7.1"
"CentOS7.1 Minimal" {0418a7c3-43bd-48ac-9574-13a4649dad45}

#執行打包操作
[flying@lemp ~]$ vagrant package --base "CentOS7.1 Minimal" --output ~/CentOS7.box
==> CentOS7.1 Minimal: Exporting VM...
==> CentOS7.1 Minimal: Compressing package to: /home/flying/CentOS7.box

#查看生成的box文件
[flying@lemp ~]$ ls -lh ~/CentOS7.box
-rw-rw-r-- 1 flying flying 834M Mar 23 10:40 /home/flying/CentOS7.box
[flying@lemp ~]$

Vagrant Box Add

將創建的box添加到vagrant box

#查看vagrant box列表
[flying@lemp ~]$ vagrant box list
MariaDB101 (virtualbox, 0)

#將box加入vagrant box列表,命名爲CentOS7Minimal
[flying@lemp ~]$ vagrant box add CentOS7Minimal ~/CentOS7.box
==> box: Box file was not detected as metadata. Adding it directly...
==> box: Adding box 'CentOS7Minimal' (v0) for provider:
    box: Unpacking necessary files from: file:///home/flying/CentOS7.box
==> box: Successfully added box 'CentOS7Minimal' (v0) for 'virtualbox'!

#查看vagrant box列表
[flying@lemp ~]$ vagrant box list
CentOS7Minimal (virtualbox, 0)
MariaDB101     (virtualbox, 0)
[flying@lemp ~]$

Vagrant init & up

使用新建的vagrant box CentOS7Minimal創建虛擬機

#查看vagrant box列表
[flying@lemp ~]$ vagrant box list
CentOS7Minimal (virtualbox, 0)
MariaDB101     (virtualbox, 0)

#進入目錄~/vagrant/
[flying@lemp ~]$ cd ~/vagrant/

#列出已有的vagrant虛擬機
[flying@lemp vagrant]$ ls
mariadb  MariaDBReplication

#創建目錄centos7
[flying@lemp vagrant]$ mkdir -pv centos7
mkdir: created directory ‘centos7’

#進入目錄
[flying@lemp vagrant]$ cd centos7/

#vagrant初始化
[flying@lemp centos7]$ vagrant init CentOS7Minimal
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.

#列出目錄下文件
[flying@lemp centos7]$ ls -lhA
total 4.0K
drwxrwxr-x 3 flying flying   21 Mar 23 10:48 .vagrant
-rw-rw-r-- 1 flying flying 3.0K Mar 23 10:48 Vagrantfile

#編輯配置文件,取消'config.vm.network "public_network"'註釋
[flying@lemp centos7]$ vim Vagrantfile

#啓動虛擬機
[flying@lemp centos7]$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'CentOS7Minimal'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: centos7_default_1458701330138_53501
==> default: Clearing any previously set network interfaces...
==> default: Available bridged network interfaces:
1) wlp3s0
2) virbr0
3) enp5s0
==> default: When choosing an interface, it is usually the one that is
==> default: being used to connect to the internet.

#選額使用的橋接網卡
    default: Which interface should the network bridge to? 1
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
    default: Adapter 2: bridged
==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (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:
    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!
GuestAdditions 5.0.16 running --- OK.
==> default: Checking for guest additions in VM...
==> default: Configuring and enabling network interfaces...
==> default: Mounting shared folders...
    default: /vagrant => /home/flying/vagrant/centos7
[flying@lemp centos7]$

Vagrant ssh & halt

#ssh登入虛擬機
[flying@lemp centos7]$ vagrant ssh
Last login: Tue Mar 22 23:44:29 2016

#當前相同用戶
[vagrant@localhost ~]$ whoami
vagrant

#退出登錄
[vagrant@localhost ~]$ exit
logout
Connection to 127.0.0.1 closed.

#關閉虛擬機
[flying@lemp centos7]$ vagrant halt
==> default: Attempting graceful shutdown of VM...
[flying@lemp centos7]$

以上即所有操作過程,成功實現創建個人box

更新: 在網路上找到一篇 How to Create a CentOS Vagrant Base Box,與本人研究出來的過程有較大不同。

Vagrant Multiple Host Configuration

以下是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.

boxes = [
    { :name => :master,       :role => 'db', :ip => '192.168.0.120' }, # master node
    { :name => :slave1,       :role => 'db', :ip => '192.168.0.121' }, # classical replication node
    { :name => :slave2,       :role => 'db', :ip => '192.168.0.122' }, # gtid replication node
    { :name => :loadbalancer, :role => 'lb', :ip => '192.168.0.123' }, # load balancer
]

$common=<<SCRIPT
    sudo yum install -y chrony
SCRIPT

Vagrant.configure(2) do |config|
    config.vm.box = "MariaDB101"

    boxes.each do |opts|
        config.vm.define opts[:name] do |config|
            #config.ssh.username = 'vagrant'
            #config.ssh.password = 'vagrant'
            config.vm.network "public_network", bridge: "wlp3s0"
            #config.vm.network "public_network",ip: opts[:ip],bridge: "wlp3s0"
            config.vm.host_name = "%s.vm" % opts[:name].to_s
            # config.vm.provision "shell", inline: $install_common
            # config.ssh.insert_key = false
            config.vm.provision "shell", inline: $common
            if opts[:role] == 'lb'
                config.vm.provision "shell", inline: <<-SHELL
                    sudo yum install -y haproxy
                SHELL
            end
        end
    end
end

References

Change Logs

  • 2016.03.23 10:57 Wed Asia/Beijing
    • 初稿完成
  • 2016.03.23 14:53 Wed Asia/Beijing
    • 內容更新
  • 2016.04.03 11:07 Sun Asia/Beijing
    • 添加Vagrant Multiple Host Configuration

  • Note Time: 2016.03.23 10:57 Wed
  • Note Location: Asia/Beijing
  • Writer: lempstacker