vagrant流浪汉入门


备注

Vagrant是一种用于创建和配置虚拟开发环境的软件工具。它可以作为VirtualBox或VMware等其他虚拟化软件的包装。 Vagrant本身就是一个命令行实用程序。

使用Ruby编写的特殊Vagrantfile配置配置Vagrant框,但可能包含用bash,Chef或Puppet编写的其他配置脚本。团队中的开发人员可以从公共源下载Vagrant配置文件,并在本地重新创建相同的开发环境。

有用的链接

版本

下载更新日志发布日期
1.8.5 下载 更新日志 2016年7月18日
1.8.4 下载 更新日志 2016年6月13日
1.8.3 下载 更新日志 2016年6月10日
1.8.1 下载 更新日志 2015年12月24日
1.8.0 下载 更新日志 2015年12月21日
1.7.4 下载 更新日志 2015年7月17日
1.7.3 下载 更新日志 2015年7月10日
1.7.2 下载 更新日志 2015年1月6日
1.7.1 下载 更新日志 2014-12-12
1.7.0 下载 更新日志 情节中字
1.6.5 下载 更新日志 2014年9月4日
1.6.4 下载 更新日志 2014年9月2日
1.6.3 下载 更新日志 2014年5月29日
1.6.2 下载 更新日志 2014年5月12日
1.6.1 下载 更新日志 2014年5月8日
1.6.0 下载 更新日志 2014年5月6日

在几分钟内完成虚拟linux的最简单方法(分3步)

步骤1。

在主机(Windows / Linux / OSX)中,创建一个空目录my_project

第2步。

使用以下命令创建名为Vagrantfile 的文件:

Vagrant.configure("2") do |config|
  config.vm.box = "gbarbieru/xenial" #An Ubuntu 16.04 based image
  config.vm.hostname = "my_project"
  config.vm.network :private_network, ip: "172.16.123.10"
end
 

第3步。

运行你的机器:

host$ vagrant up
host$ vagrant ssh
virtual$ cd /vagrant
 

完成!


笔记:

  • 也许你想分配另一个IP地址。
  • 如果你的主机是Windows,也许你想从putty ssh 。您可以通过ssh到主机名127.0.0.1 和端口2222 。用户名是vagrant ,密码是vagrant

使用VirtualBox和SSH支持的Windows安装

要在Windows平台上使用Vagrant,您需要先安装虚拟化软件和ssh命令行工具。这个例子将使用免费软件VirtualBox和Cygwin。

安装VirtualBox

官方下载页面下载最新的VirtualBox版本并运行下载的文件。请注意,在安装过程中,您将暂时失去网络连接。 警告:网络接口

您还应该让Oracle安装其他驱动程序。

安装Cygwin

cygwin.com获取并运行设置,直到您获得“选择包”页面。

我们只需要来自这里的ssh bin-s: Cygwin SSH包

将Cygwin添加到PATH

您还需要将C:\cygwin64\bin 文件夹添加到Windows PATH环境变量中。这样你就可以从任何地方调用ssh 命令。

安装Vagrant本身

vagrantup.com下载Vagrant,然后按照设置指南进行安装。此后必须重新启动计算机。

测试

应启用虚拟化技术VTx / VTd。 (您可以在安全选项的BIOS中找到)

要测试是否正确安装了所有内容,请在硬盘驱动器上的某处创建一个空文件夹,打开命令行并移至刚刚创建的文件夹:

cd c:/path/to/your/folder
 

然后进入

vagrant init hashicorp/precise64
vagrant up
 

这将创建并启动运行Ubuntu 12.04 LTS 64位的VirtualBox。要启动32位版本,请使用vagrant init hashicorp/precise32 。如果您需要另一个盒子,您可以在hashicorp网站上找到更多信息

vagrant init 命令还将在当前文件夹中创建Vagrantfile 配置文件。现在您可以将其发送给其他人,当该人呼叫vagrant up 时,将在他/她的PC上创建相同的虚拟机。

要在这两个命令成功运行后测试ssh,请在同一文件夹中运行此命令:

vagrant ssh
 

如果一切顺利,您将最终进入以vagrant 用户身份登录的虚拟机。

进一步的步骤

您可以使用停止VM

vagrant halt
 

或删除它

vagrant destroy
 

可以在vagrantbox.es页面上找到更多框以及如何安装它们的说明。

LAMP项目

在此示例中,使用Vagrant创建自定义LAMP项目开发环境。

首先,您需要安装Virtual BoxVagrant

然后,在主目录中创建一个vagrant 文件夹,打开终端并将当前目录更改为新的vagrant 目录。现在,执行vagrant init 。将在里面创建一个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.
Vagrant.configure(2) do |config|
  # The most common configuration options are documented and commented below.
  # For a complete reference, please see the online documentation at
  # https://docs.vagrantup.com.

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://atlas.hashicorp.com/search.
  config.vm.box = "base"

  # Disable automatic box update checking. If you disable this, then
  # boxes will only be checked for updates when the user runs
  # `vagrant box outdated`. This is not recommended.
  # config.vm.box_check_update = false

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine. In the example below,
  # accessing "localhost:8080" will access port 80 on the guest machine.
  # config.vm.network "forwarded_port", guest: 80, host: 8080

  # Create a private network, which allows host-only access to the machine
  # using a specific IP.
  # config.vm.network "private_network", ip: "192.168.33.10"

  # Create a public network, which generally matched to bridged network.
  # Bridged networks make the machine appear as another physical device on
  # your network.
  # config.vm.network "public_network"

  # Share an additional folder to the guest VM. The first argument is
  # the path on the host to the actual folder. The second argument is
  # the path on the guest to mount the folder. And the optional third
  # argument is a set of non-required options.
  # config.vm.synced_folder "../data", "/vagrant_data"

  # Provider-specific configuration so you can fine-tune various
  # backing providers for Vagrant. These expose provider-specific options.
  # Example for VirtualBox:
  #
  # config.vm.provider "virtualbox" do |vb|
  #   # Display the VirtualBox GUI when booting the machine
  #   vb.gui = true
  #
  #   # Customize the amount of memory on the VM:
  #   vb.memory = "1024"
  # end
  #
  # View the documentation for the provider you are using for more
  # information on available options.

  # Define a Vagrant Push strategy for pushing to Atlas. Other push strategies
  # such as FTP and Heroku are also available. See the documentation at
  # https://docs.vagrantup.com/v2/push/atlas.html for more information.
  # config.push.define "atlas" do |push|
  #   push.app = "YOUR_ATLAS_USERNAME/YOUR_APPLICATION_NAME"
  # end

  # Enable provisioning with a shell script. Additional provisioners such as
  # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the
  # documentation for more information about their specific syntax and use.
  # config.vm.provision "shell", inline: <<-SHELL
  #   sudo apt-get update
  #   sudo apt-get install -y apache2
  # SHELL
end
 

添加或取消注释编辑上述文件的下一行:

config.vm.box = "hashicorp/precise64"
config.vm.network :forwarded_port, guest: 80, host: 8080
config.vm.network :private_network, ip: "192.168.33.10"
config.ssh.forward_agent = true
if Vagrant::Util::Platform.windows?
  config.vm.synced_folder "./", "/vagrant"
else
  config.vm.synced_folder "./", "/vagrant", type: "nfs"
end
# https://stefanwrobel.com/how-to-make-vagrant-performance-not-suck
config.vm.provider "virtualbox" do |v|
  host = RbConfig::CONFIG['host_os']

  # Give VM 1/4 system memory & access to all cpu cores on the host
  if host =~ /darwin/
    cpus = `sysctl -n hw.ncpu`.to_i
    # sysctl returns Bytes and we need to convert to MB
    mem = `sysctl -n hw.memsize`.to_i / 1024 / 1024 / 4
  elsif host =~ /linux/
    cpus = `nproc`.to_i
    # meminfo shows KB and we need to convert to MB
    mem = `grep 'MemTotal' /proc/meminfo | sed -e 's/MemTotal://' -e 's/ kB//'`.to_i / 1024 / 4
  else # sorry Windows folks, I can't help you
    cpus = 2
    mem = 1024
  end

  v.customize ["modifyvm", :id, "--memory", mem]
  v.customize ["modifyvm", :id, "--cpus", cpus]
end
 

编辑hosts 文件,将所需域重定向到vagrant VM。对于Linux,它使用/etc/hosts ,对于Windows C:\Windows\System32\Drivers\etc\hosts ;并添加此行:

192.168.33.10 vagrantServer.com
 

当然,您可以用任何名称替换vagrantServer.com

现在是时候创建bootstrap.sh 文件了(在vagrant 目录中)。每次从头开始生成VM时,都会执行此脚本。仔细阅读评论:

#!/usr/bin/env bash

# .ssh/authorized_keys (you will need to create a `.ssh` directory inside the `vagrant` one and add a file named `authorized_keys` with the public keys of the users who have access to the repository and may use this environment).
# You also will have to grant access to those public keys from the Github account, Bitbucket, or whatever you're using.
cat /vagrant/config/authorized_keys >> /home/vagrant/.ssh/authorized_keys
if ! [ -d /root/.ssh ]; then
  mkdir /root/.ssh
fi
cp /vagrant/config/authorized_keys /root/.ssh
chmod 600 /root/.ssh/authorized_keys

# Install packages
apt-get update
apt-get install -y python-software-properties
add-apt-repository ppa:ondrej/php5 -y
apt-get update
apt-get install -y curl nano apache2 php5 php5-mysql php5-curl php5-gd php5-intl php5-mcrypt git

# Apache2 run with user vagrant
APACHEUSR=`grep -c 'APACHE_RUN_USER=www-data' /etc/apache2/envvars`
APACHEGRP=`grep -c 'APACHE_RUN_GROUP=www-data' /etc/apache2/envvars`
if [ APACHEUSR ]; then
    sed -i 's/APACHE_RUN_USER=www-data/APACHE_RUN_USER=vagrant/' /etc/apache2/envvars
fi
if [ APACHEGRP ]; then
    sed -i 's/APACHE_RUN_GROUP=www-data/APACHE_RUN_GROUP=vagrant/' /etc/apache2/envvars
fi
sudo chown -R vagrant:www-data /var/lock/apache2

# Set user/password to mysql previously to installation
# Replace rootMysqlPassword with your desired MySQL root password
debconf-set-selections <<< 'mysql-server mysql-server/root_password password rootMysqlPassword'
debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password rootMysqlPassword'

# Install mysql
apt-get update
apt-get install -y mysql-server mysql-client

# Link /vagrant (sync_folder) to apache directory (/var/www)
if ! [ -L /var/www ]; then
  rm -rf /var/www
  ln -fs /vagrant /var/www
fi

# Install composer
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

# Composer example. Uncoment to istall phpunit
#composer global require "phpunit/phpunit=3.7.*" --prefer-source

# Create mysql database (replace "vagrantDB" with any desired database name, and "rootMysqlPassword" with the password set above)
mysql -u root -prootMysqlPassword -v -e "CREATE USER 'developer'@'%' IDENTIFIED BY 'dev'; 
CREATE SCHEMA vagrantDB;
GRANT ALL ON vagrantDB TO 'developer'@'%';"

# Uncomment to set default database fixtures based on `/vagrant/config/vagrantDBFixtures.sql` file.
#mysql -u root -prootMysqlPassword -v vagrantDB < /vagrant/config/vagrantDBFixtures.sql

###################################################
################ THIS IS OPTIONAL #################
###################################################

# Install nodejs
curl -sL https://deb.nodesource.com/setup | sudo bash -
apt-get install -y nodejs

# Install npm packages
npm install -g npm
npm install -g bower
npm install -g forever
npm install -g gulp

# Set accepted license before install java
echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections
echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections

# Install java7
apt-get install -y oracle-java7-installer oracle-java7-set-default

###################################################
################### END OPTIONAL ##################
###################################################

# Generate ssh key without passphrase
ssh-keygen -f /root/.ssh/id_rsa -t rsa -N ""

# Add bitbucket and github to known hosts
touch /root/.ssh/known_hosts
ssh-keyscan -H bitbucket.org >> /root/.ssh/known_hosts
ssh-keyscan -H github.com >> /root/.ssh/known_hosts

# Source: https://gist.github.com/winhamwr/7122947
# Sleep until we can successfully SSH into Bitbucket.
# Uses doublinng backoff while waiting 
# with_backoff() adapted from http://stackoverflow.com/a/8351489
# Retries a command a configurable number of times with backoff.
#
# The retry count is given by ATTEMPTS (default 5), the initial backoff
# timeout is given by TIMEOUT in seconds (default 1.)
#
# Successive backoffs double the timeout.
#generatedKey="`cat /root/.ssh/id_rsa.pub`"
echo -n "Generate a SSH key (https://help.github.com/articles/generating-ssh-keys/) 
and add it to your Bitbucket account (Profile -> SHH keys) to continue. "

with_backoff() {
  local max_attempts=${ATTEMPTS-5}
  local timeout=${TIMEOUT-1}
  local attempt=0
  local exitCode=0
 
  while [ $attempt -lt $max_attempts ]
  do
    set +e
    "$@"
    exitCode=$?
    set -e
 
    if [ $exitCode -eq 0 ]
    then
      break
    fi
 
    echo "Failure! Retrying in $timeout.." 1>&2
    sleep $timeout
    attempt=$(( attempt + 1 ))
    timeout=$(( timeout * 2 ))
  done
 
  if [ $exitCode -ne 0 ]
  then
    echo "You've failed me for the last time! ($@)" 1>&2
  fi
 
  return $exitCode
}
 
ATTEMPTS=${ATTEMPTS:-5}
 
export ATTEMPTS
with_backoff ssh -T git@bitbucket.org;

# Clone repositories (replace "yourProjectName" and "yourProjectRepository" with your project data)
cd /var/www
rm -rf yourProjectName/
git clone yourProjectRepository

# Add server names to /etc/hosts (replace "vagrantServer.com" with the domain set above)
echo -e '\n127.0.0.1       vagrantServer.com' >> /etc/hosts

# Enable apache modes
a2enmod rewrite

# Copy sites-available file (you need to add the Apache configuration file for the desired domain in `config/sites-available`. Replace "vagrantServer.conf" with the desired name)
cp /vagrant/config/sites-available/vagrantServer.conf /etc/apache2/sites-available/

# Remove html from document root
sed -i 's/\/var\/www\/html/\/var\/www/g' /etc/apache2/sites-available/*
service apache2 restart

# Enable sites (replace "vagrantServer.conf" with the above file name)
a2ensite vagrantServer.conf

# Install ruby, compass and sass (Optional)
apt-get install -y rubygems
gem install compass
npm install -g sass

# Pull the repo
cd /var/www/yourProjectName
git pull --all
 

一旦检查并保存上述文件,去你的终端再次,改变当前目录到vagrant 您之前曾创建过一个和类型vagrant up 。将创建VM,并从VM执行boostrap文件,因此将复制/安装所有需要的东西。完成后,您可以打开浏览器并访问vagrantServer.com (或您提供的任何名称),您应该看到流浪汉VM提供的内容。

您也可以通过编辑您的项目文件vagrant/yourProjectName 目录和里面的所有文件vagrant 目录将被共享和你的主机和虚拟机的流浪汉之间同步。

同步所有文件夹

要同时向两个方向同步所有文件夹,请将其插入到Vagrantfile

config.vm.synced_folder "my-project1", "/home/vagrant/my-project1"
 

同步文件夹但排除某些文件夹

要在两个方向同步所有文件夹,请将其插入到Vagrantfile中:

config.vm.synced_folder "my-project1", "/home/vagrant/my-project1", type: "rsync",
 :rsync__exclude => ['my-project1/mini_project2/target,my-project1/mini_project2/target,my-project1/mini_project3/target']
 

从同步中排除所有目标文件夹。
同步只发生在vagrant upvagrant reload
要同步您从主机到访客的每个更改,您必须使用:

vagrant rsync-auto
 

将Vagrant Box图像上传到Amazon AWS AMI

您有一个要上传到Amazon AWS的本地流浪者框。首先,您需要创建一个.box 文件:

vagrant package --base my-virtual-machine

此步骤需要一段时间,具体取决于图像的大小。然后,您需要从.box 文件中获取.vmdk 图像:

gunzip -S .box package.box
tar xf package
 

完成此步骤后,您应该有4个新文件: packagebox-disk1.vmdkVagrantfilebox.ovf 。现在,上传到AWS。假设您拥有AWS账户 ,请创建一个S3存储桶以将图像存储在Amazon的服务器上。您将需要亚马逊的EC2 CLI进行下一步(据我所知,您无法通过控制台执行此操作):

ec2-import-instance box-disk1_1.vmdk -f VMDK -t t2.micro -a x86_64 -b <S3-bucket-name> -o $AWS_ACCESS_KEY -w $AWS_SECRET_KEY -p Linux

此命令的结果应该需要一段时间 - 它将大图像文件上传到S3,但命令本身返回的速度更快。您可以使用ec2-describe-conversion-tasks 命令检查导入的进度。

完成后,您将在AWS控制台中看到您的盒子的实例正在运行。但是,您可能无法访问它,因为它没有公共IP地址和/或没有与之关联的.pem 文件。因此,下一步是从实例创建AMI。要创建AMI,请停止实例(不要终止!)并右键单击实例并转到Image - > Create Image 。这也需要一段时间。您可以在控制台的AMI视图中查看进度。一旦完成,使用AMI附加启动一个实例.pem 密钥文件,然后你可以ssh 的,你是好去。