Supercharged development environments
Содержание:
- »Creating a Base Box
- »Windows Boxes
- »Upgrading to v1.x
- Sahara
- »Defining Multiple Machines
- »Default User Settings
- Общие папки
- Pricing & Purchase
- VMware Makes Your Life Better
- Создание Vagrantfile
- Frequently Asked Questions
- Сетевые настройки
- »Frequently Asked Questions
- »Other Software
- Создание базовых сборок
- »Linked Clones
- »Providers
- »Vagrant Up
- Заключение
»Creating a Base Box
Creating a base box is actually provider-specific. This means that depending
on if you are using VirtualBox, VMware, AWS, etc. the process for creating
a base box is different. Because of this, this one document cannot be a
full guide to creating a base box.
This page will document some general guidelines for creating base boxes,
however, and will link to provider-specific guides for creating base
boxes.
Provider-specific guides for creating base boxes are linked below:
- Docker Base Boxes
- Hyper-V Base Boxes
- VMware Base Boxes
- VirtualBox Base Boxes
Packer and Vagrant Cloud
We strongly recommend using Packer to create reproducible
builds for your base boxes, as well as automating the builds. Read more about
automating Vagrant box creation with Packer
in the Packer documentation.
Disk Space
When creating a base box, make sure the user will have enough disk space
to do interesting things, without being annoying. For example, in VirtualBox,
you should create a dynamically resizing drive with a large maximum size.
This causes the actual footprint of the drive to be small initially, but
to dynamically grow towards the max size as disk space is needed, providing
the most flexibility for the end user.
If you are creating an AWS base box, do not force the AMI to allocate
terabytes of EBS storage, for example, since the user can do that on their
own. But you should default to mounting ephemeral drives, because they’re
free and provide a lot of disk space.
Memory
Like disk space, finding the right balance of the default amount of memory
is important. For most providers, the user can modify the memory with
the Vagrantfile, so do not use too much by default. It would be a poor
user experience (and mildly shocking) if a from a base box
instantly required many gigabytes of RAM. Instead, choose a value such
as 512MB, which is usually enough to play around and do interesting things
with a Vagrant machine, but can easily be increased when needed.
Peripherals (Audio, USB, etc.)
Disable any non-necessary hardware in a base box such as audio and USB
controllers. These are generally unnecessary for Vagrant usage and, again,
can be easily added via the Vagrantfile in most cases.
»Windows Boxes
Supported Windows guest operating systems:
- Windows 7
- Windows 8
- Windows Server 2008
- Windows Server 2008 R2
- Windows Server 2012
- Windows Server 2012 R2
Windows Server 2003 and Windows XP are not supported, but if you are a die
hard XP fan this may help you.
Base Windows Configuration
- Turn off UAC
- Disable complex passwords
- Disable «Shutdown Tracker»
- Disable «Server Manager» starting at login (for non-Core)
In addition to disabling UAC in the control panel, you also must disable
UAC in the registry. This may vary from Windows version to Windows version,
but Windows 8/8.1 use the command below. This will allow some things like
automated Puppet installs to work within Vagrant Windows base boxes.
Base WinRM Configuration
To enable and configure WinRM you will need to set the WinRM service to
auto-start and allow unencrypted basic auth (obviously this is not secure).
Run the following commands from a regular Windows command prompt:
Additional WinRM 1.1 Configuration
These additional configuration steps are specific to Windows Server 2008
(WinRM 1.1). For Windows Server 2008 R2, Windows 7 and later versions of
Windows you can ignore this section.
- Ensure the Windows PowerShell feature is installed
- Change the WinRM port to 5985 or upgrade to WinRM 2.0
The following commands will change the WinRM 1.1 port to what’s expected by
Vagrant:
Optional WinSSH Configuration
When using the WinSSH communicator, you may run into an issue where a PowerShell
command can’t display a progress bar. A typical error message might look like:
In order to prevent this, we recommend setting
in your box’s PowerShell profile:
»Upgrading to v1.x
It is extremely important that the VMware plugin is upgraded to 1.0.0 or
above. This release resolved critical security vulnerabilities. To learn more,
please read our release announcement.
After upgrading, please verify that the following paths are empty. The upgrade
process should remove these for you, but for security reasons it is important
to double check. If you’re a new user or installing the VMware provider on a
new machine, you may skip this step. If you’re a Windows user, you may skip this
step as well.
The path
should no longer exist. The gem may exist since this
is the name of the new plugin. If the old directories exist, remove them. An
example for a Unix-like shell is shown below:
Sahara
Плагин представляет собой песочницу для виртуальных машин: если что-то поломалось, можно легко и просто откатить до последнего снэпшота. Плагин является руби-гемом (что вполне ожидаемо) и называется sahara. После его установки в вагранте появляется дополнительная команда — vagrant sandbox. Типичный пример использования выглядит так. Включаем режим песочницы:
Производим определенные действия (работаем с файлами, меняем настройки и прочее):
Если результат работы нас удовлетворил — сохраняем изменения:
В противном случае откатываем неугодные правки:
И выходим из режима песочницы:
»Defining Multiple Machines
Multiple machines are defined within the same project Vagrantfile
using the method call. This configuration directive
is a little funny, because it creates a Vagrant configuration within a
configuration. An example shows this best:
As you can see, takes a block with another variable. This
variable, such as above, is the exact same as the variable,
except any configuration of the inner variable applies only to the machine
being defined. Therefore, any configuration on will only affect the
machine.
And importantly, you can continue to use the object as well. The
configuration object is loaded and merged before the machine-specific configuration,
just like other Vagrantfiles within the
.
If you are familiar with programming, this is similar to how languages have
different variable scopes.
When using these scopes, order of execution for things such as
provisioners becomes important. Vagrant enforces ordering outside-in, in
the order listed in the Vagrantfile. For example, with the Vagrantfile
below:
The provisioners in this case will output «A», then «C», then «B». Notice
that «B» is last. That is because the ordering is outside-in, in
the order of the file.
If you want to apply a slightly different configuration to multiple machines,
see .
»Default User Settings
Just about every aspect of Vagrant can be modified. However, Vagrant does
expect some defaults which will cause your base box to «just work» out
of the box. You should create these as defaults if you intend to publicly
distribute your box.
If you are creating a base box for private use, you should try not to
follow these, as they open up your base box to security risks (known
users, passwords, private keys, etc.).
«vagrant» User
By default, Vagrant expects a «vagrant» user to SSH into the machine as.
This user should be setup with the
insecure keypair
that Vagrant uses as a default to attempt to SSH. Also, even though
Vagrant uses key-based authentication by default, it is a general convention
to set the password for the «vagrant» user to «vagrant». This lets people
login as that user manually if they need to.
To configure SSH access with the insecure keypair, place the public
key into the file for the «vagrant» user. Note
that OpenSSH is very picky about file permissions. Therefore, make sure
that has permissions and the authorized keys file has
permissions.
When Vagrant boots a box and detects the insecure keypair, it will
automatically replace it with a randomly generated keypair for additional
security while the box is running.
Root Password: «vagrant»
Vagrant does not actually use or expect any root password. However, having
a generally well known root password makes it easier for the general public
to modify the machine if needed.
Publicly available base boxes usually use a root password of «vagrant» to
keep things easy.
Password-less Sudo
This is important!. Many aspects of Vagrant expect the default SSH user
to have passwordless sudo configured. This lets Vagrant configure networks,
mount synced folders, install software, and more.
To begin, some minimal installations of operating systems do not even include
by default. Verify that you install in some way.
After installing sudo, configure it (usually using ) to allow
passwordless sudo for the «vagrant» user. This can be done with the
following line at the end of the configuration file:
Additionally, Vagrant does not use a pty or tty by default when connected
via SSH. You will need to make sure there is no line that has in
it. Remove that if it exists. This allows sudo to work properly without a
tty. Note that you can configure Vagrant to request a pty, which lets
you keep this configuration. But Vagrant by default does not do this.
SSH Tweaks
In order to keep SSH speedy even when your machine or the Vagrant machine
is not connected to the internet, set the configuration to
in the SSH server configuration.
This avoids a reverse DNS lookup on the connecting SSH client which
can take many seconds.
Общие папки
Еще одна интересная особенность VirtualBox — общие папки, дающие возможность легко обмениваться файлами между гостевой и хост-машинами. Разумеется, Vagrant предоставляет удобный способ настройки данной опции. Все, что нужно, — это немного поправить конфигурационный файл:
Важно заметить также, что папки, использующие протокол NFS (Network File System), показывают лучшую производительность, нежели общие папки виртуалбокса. С другой стороны, NFS не поддерживается на хостах с Windows
Для того чтобы использовать NFS вместо VirtualBox shared folders, необходимо это явно указать в настройках:
Pricing & Purchase
Price: $79 per seat.
A single seat can be used on two computers (such as a desktop and a laptop) for a single person. The license is valid forever with access to free maintenance updates. Future major updates may require an upgrade fee.
VMware Fusion 12 / VMware Workstation 16 or lower
The provider license does not include a license to the VMware software, which must be purchased separately. If you are buying over 150 licenses, contact sales@hashicorp.com for volume pricing. By purchasing this license, you agree to the EULA and the HashiCorp Privacy Policy and Terms of Service.
Previous plugin versions may not support the latest VMware products. Please visit the license upgrade center to check if your license requires an upgrade before you upgrade your VMware products.
VMware Makes Your Life Better
-
, , — the same Vagrant workflow you know and love. Vastly improve your work environments without having to re-educate your team.
-
The VMware hypervisor has been in production use since 1999. All their products share the same, robust core that powers the world‘s largest organizations. With the VMware provider, Vagrant now runs on the strength of the same foundation.
-
VMware screams, with industry-leading performance1 based on the same hypervisor technology in use by 98% of the Fortune 500. Get all the performance gains paired with the ease of use of Vagrant.
-
VMware virtual machines run on Mac OS X, Windows, and Linux. Vagrant provides support for both VMware Fusion (Mac OS X) and VMware Workstation (Linux and Windows), which are able to run the same virtual machines across multiple platforms.
-
Vagrant Open Source
Vagrant is free and open source. While the VMware providers are not, the revenue is used to continue to develop, support, and grow Vagrant and the community around it.
Создание Vagrantfile
Теперь создадим файл конфигурации:
$ vagrant init -m ubuntu/bionic64 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.
Использование ключа или позволяет создать файл Vagrantfile минимального размера, без комментариев. Есть смысл использовать команду без этого ключа и прочитать комментарии — там много интересного.
Посмотрим на файл :
Vagrant.configure(2) do |config| config.vm.box = "ubuntu/bionic64" end
При создании мы указали название бокса . Бокс — это образ операционной системы, который так же может содержать установленные программы (LAMP, Python и т.д). Подходящий бокс можно найти на сайте Vagtant Cloud. Разработчики Vagrant рекомендуют использовать образы Bento.
В принципе, этого достаточно, чтобы создать виртуальную машину. Но давайте немного доработаем конфигурацию:
Vagrant.configure(2) do |config| # образ системы Ubuntu 18/04 LTS (Bionic Beaver) config.vm.box = "bento/ubuntu-18.04" # не проверять репозиторий на наличие обновлений config.vm.box_check_update = false config.vm.provider "virtualbox" do |vb| # имя виртуальной машины vb.name = "ubuntu-1804-test" # объем оперативной памяти vb.memory = 2048 # количество ядер процессора vb.cpus = 1 end # hostname виртуальной машины config.vm.hostname = "ubuntu-1804-test" end
Создаем виртуальную машину. В первый раз процесс займет больше времени, Vagrant должен скачать образ с операционной системой.
$ vagrant up
Остановить виртуальную машину можно командой
$ vagrant halt
Чтобы посмотреть справку по всем командам:
$ vagrant --help Usage: vagrant <command> -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` Additional subcommands are available, but are either more advanced or not commonly used. To see all subcommands, run the command `vagrant list-commands`.
Frequently Asked Questions
-
We do not offer a trial mechanism at this time, but we do offer a 30-day, no questions asked, 100% money-back guarantee. If you are not satisfied with the product, contact us within 30 days and you will receive a full refund.
-
Do you offer educational discounts on the Vagrant VMware plugins?
We offer an academic discount of 10% for the Vagrant VMware plugins. However, we require proof that you are a current student or employee in academia. Please contact support with any one of the following forms of proof:
- A picture of your current university ID
- An email from your official school email address
- A copy of something on university letterhead indicating you are currently enrolled as a student
-
Existing license holders may check their upgrade eligibility by visiting the license upgrade center. If you are eligible for an upgrade, the system will generate a unique discount code that may be used when purchasing the new license.
-
Please note: your existing license will continue to work with all previous versions of the VMware products. If you do not wish to update at this time, you can rollback your VMware installation to an older version.
-
The EULA for the Vagrant VMware plugins is available on the Vagrant website.
-
All our reseller information can be found on the Reseller Information page.
-
The Vagrant VMware Plugin requires the separate purchase of VMware Fusion/Workstation from VMware. The VMware product is not bundled with the plugin.
-
Please try restarting your computer and running the VMware software manually. Occasionally you must accept the license agreement before VMware will run. If you do not see any errors when opening the VMware GUI, you may need to purchase the full version to use the plugin. We apologize for the inconvenience.
-
Some features of the Vagrant VMware Workstation plugin will work with VMware Player, but it is not officially supported. Vagrant interacts with VMware via the VMware API, and some versions of VMware Workstation Player do not support those APIs. When in doubt, please purchase VMware Workstation Pro to use all the features supported by the integration.
-
Do I need VMware Fusion/Workstation Pro or just the regular version?
The Vagrant VMware plugin is compatible with both the regular and Pro versions of VMware Fusion and VMware Workstation. However, some advanced features (such as linked clones), are only supported by the Pro versions of the VMware software.
Please consult the VMware documentation to determine which features are supported by the Pro and non-Pro versions to determine which product you need to purchase.
Сетевые настройки
Конечно, одна из важнейших настроек виртуальной машины — конфигурация сетевых интерфейсов. За сетевые настройки отвечает параметр config.vm.network. Вагрант предлагает два варианта на выбор: работа в сети, ограниченной хост-машиной, и подключение через сетевой мост.
В первом случае мы явно задаем IP машины, а также можем опционально указать маску сети (по умолчанию используется 255.255.255.0). В таком случае конфиг приобретает вид:
Во втором случае машина получает IP по DHCP и становится полноценным членом сети, в которой расположена и хост-машина. Если на хост-машине присутствует несколько сетевых интерфейсов, то мы можем указать, который именно использовать для моста. Для вывода списка имен сетевых интерфейсов воспользуемся командой:
И, соответственно, конфигурация примет вид:
Кроме того, Vagrant позволяет также пробрасывать порты. Вот, например, такой Vagrantfile позволяет пробрасывать с 6379-го порта гостевой машины, на который по умолчанию вешается редис, на 8765-й на хост-машине.
Какой вариант лучше — выбор за тобой, но в любом случае наша виртуалка уже вполне может выполнять роль сервера базы данных, на который можно зайти либо с хост-машины, либо с другой виртуалки.
Также в VB 4.2 значительно улучшился общий интерфейс работы с машинами
»Frequently Asked Questions
Q: Can Vagrant VMware Plugin work without internet?
No, Vagrant VMware plugin requires a new license every 6 weeks. Vagrant will try to renew the
license automatically. If you are on an environment without internet, after 4 weeks Vagrant will emit a warning,
and after 6 weeks, the VMware plugin will stop working. You can install a new license to reactive vagrant.
Q: Do I need to keep the Vagrant VMware plugin license file on disk?
After you have installed the Vagrant VMware plugin license, it is safe to remove
your copy from disk. Vagrant copies the license into its structure for reference
on boot.
Q: I upgraded my VMware product and now my license is invalid?
Your existing license will continue to work with all previous versions of the
VMware products. If you do not wish to update at this time, you can rollback
your VMware installation to an older version.
Q: Why is the Vagrant VMware plugin not working with my trial version of VMware Fusion/Workstation?
The Vagrant VMware Fusion and Vagrant VMware Workstation plugins are not
compatible with trial versions of the VMware products. We apologize for the
inconvenience.
Q: How do I upgrade my currently installed Vagrant VMware plugin?
You can update the Vagrant VMware plugin to the latest version by re-running the
install command:
»Other Software
At this point, you have all the common software you absolutely need for
your base box to work with Vagrant. However, there is some additional software
you can install if you wish.
While we plan on it in the future, Vagrant still does not install Chef
or Puppet automatically when using those provisioners. Users can use a shell
provisioner to do this, but if you want Chef/Puppet to just work out of the
box, you will have to install them in the base box.
Installing this is outside the scope of this page, but should be fairly
straightforward.
In addition to this, feel free to install and configure any other software
you want available by default for this base box.
Создание базовых сборок
Несмотря на то что сообщество уже позаботилось о наиболее распространенных образах операционных систем, тебе вполне может понадобиться иметь свою особенную сборку
Из соображений безопасности (а вдруг хакер Вася добавил свою магию в одну из сборок, лежащих в Сети), необходимости каких-то особенных настроек или просто из интереса — неважно, главное, что такая возможность есть. И здесь нам поможет гем veewee, созданный специально для этих целей
Для начала установим его:
Репозиторий veewee содержит большое количество шаблонов. Выберем интересующий нас — пусть это будет последняя версия Ubuntu Server. Теперь создадим новую базовую сборку на основе этого шаблона:
В результате у нас появится новое «определение» бейс-бокса. В папке definitions/myubuntubox содержатся файлы, описывающие нашу виртуальную машину:
Немного поправим конфигурацию виртуалки:
Теперь запустим сборку командой
Veewee задумается на время, пока будет создавать виртуальную машину, скачивать ISO-образ операционной системы, а также устанавливать и настраивать ее. После того как команда закончит работу, проверим созданную виртуалку командой
Если все прошло гладко, можно двигаться дальше. Проэкспортируем созданную виртуальную машину как файл базовой сборки vagrant:
Ну вот, собственно, и все. Теперь, чтобы использовать нашу базовую сборку, вызовем уже знакомые команды. Добавим бокс в список:
И создадим новую виртуальную машину на основе уже созданной:
Вот и все — теперь даже самые рьяные параноики не смогут нас осудить, ведь теперь весь техпроцесс создания виртуальной среды контролируется нами же.
»Linked Clones
By default new machines are created by importing the base box. For large
boxes this produces a large overhead in terms of time (the import operation)
and space (the new machine contains a copy of the base box’s image).
Using linked clones can drastically reduce this overhead.
Linked clones are based on a master VM, which is generated by importing the
base box only once the first time it is required. For the linked clones only
differencing disk images are created where the parent disk image belongs to
the master VM.
To have backward compatibility:
If you do not want backward compatibility and want to force users to
support linked cloning, you can use with 1.8.
Note: the generated master VMs are currently not removed
automatically by Vagrant. This has to be done manually. However, a master
VM can only be removed when there are no linked clones connected to it.
»Providers
Create a provider
Arguments
-
- — The name of the provider.
- — A valid URL to download this provider. If omitted, you must the Vagrant box image for this provider to Vagrant Cloud before the provider can be used.
- — Computed checksum of the box assets. When set, Vagrant will compute the checksum of the downloaded box asset and validate it matches this value.
- — Type of checksum used. Currently supported values: md5, sha1, sha256, sha384, and sha512
Response body is identical to .
Update a provider
Arguments
-
- — The name of the provider.
- — A valid URL to download this provider. If omitted, you must the Vagrant box image for this provider to Vagrant Cloud before the provider can be used.
Response body is identical to .
Response body is identical to .
Upload a provider
Prepares the provider for upload, and returns a JSON blob containing an .
The upload must begin shortly after the response is returned, otherwise the URL will expire. If the URL expires, you can request this same API method again for a new upload URL.
»Vagrant Up
Once a provider is installed, you can use it by calling
with the flag. This will force Vagrant to use that specific
provider. No other configuration is necessary!
In normal day-to-day usage, the flag is not necessary
since Vagrant can usually pick the right provider for you. More details
on how it does this is below.
If you specified a flag, you only need to do this for the
command. Once a machine is up and running, Vagrant is able to
see what provider is backing a running machine, so commands such as
, , etc. do not need to be told what provider to use.
Vagrant currently restricts you to bringing up one provider per machine.
If you have a multi-machine environment, you can bring up one machine
backed by VirtualBox and another backed by VMware Fusion, for example, but you
cannot back the same machine with both VirtualBox and
VMware Fusion. This is a limitation that will be removed in a future
version of Vagrant.
Заключение
Удобная среда разработки позволяет больше сконцентрироваться на решаемой проблеме, а не на вопросах совместимости ПО или различиях операционных систем, и это главная фишка Vagrant. С ним можно избавиться от проблем, когда на машине разработчика все работает, а на продакшене почему-то нет. Разумеется, на данный момент несколько смущает его сильная руби-ориентированность, но будем надеяться, что со временем разработчики решат и эту проблему, расширив, например, список провизоров на Python или Java. И кстати, в настоящее время идет работа по добавлению других систем виртуализации, кроме VirtualBox.