Vagrant. начало работы. часть 1

Создаём машину по-умолчанию

Для того, чтоб создать виртуальную машину со стандартными настройками вполне достаточно выполнить две команды:

vagrant init

эта команда в текущей директории создат Vagrantfile (можете посмотреть его в
vim любимом текстовом редакторе), который будет считывать следующей командой:

vagrant up

Эта команда скачает базовый образ из репозитория vagrant и на его основе создаст виртуальную машину для VirtualBox.

Маленькие прелести vagrant:
  • Автоматическое подмонтирование корневой директории (с Vagrantfile`ом) в гостя;
  • Автоматический проброс порта для ssh (хост — 2222, гость — 22);
  • Создание ssh-ключей;
  • чтоб подключиться к машине, достаточно выполнить
vagrant ssh

И всё, мы внутри гостя.

»Using the API

Vagrant Cloud provides an API for users to interact with Vagrant Cloud for experimentation, automation, or building new features and tools on top of our existing application.

Authentication

Some API endpoints require authentication to create new resources, update or delete existing resources, or to read a private resource.

Clients can authenticate using an authentication token.
The token can be passed to Vagrant Cloud one of two ways:

  1. (Preferred) Set the header to and the value of the authentication token.
  2. Pass the authentication token as an URL parameter.

Examples below will set the header, but feel free to use whichever method is easier for your implementation.

The header is also supported for backwards-compatibility.

Request and Response Format

Requests to Vagrant Cloud which include data attributes ( or /) should set the header to , and include a valid JSON body with the request.

JSON responses may include an key, which will contain an array of error strings, as well as a key.
For example:

402 Payment Required

You are trying to access a resource which is delinquent on billing.
Please contact the owner of the resource so that they can update their billing information.

403 Forbidden

You are attempting to use the system in a way which is not allowed.
There could be required request parameters that are missing, or one of the parameters is invalid.
Please check the response key, and double-check the examples below for any discrepancies.

404 Not Found

The resource you are trying to access does not exist. This may also be returned if you attempt to access a private resource that you don’t have authorization to view.

429 Too Many Requests

You are currently being rate-limited. Please decrease your frequency of usage, or contact us at support+vagrantcloud@hashicorp.com with a description of your use case so that we can consider creating an exception.

Server Errors

500 Internal Server Error

The server failed to respond to the request for an unknown reason.
Please contact support+vagrantcloud@hashicorp.com with a description of the problem so that we can investigate.

»Version Constraints

You can constrain a Vagrant environment to a specific version or versions
of a box using the Vagrantfile by specifying
the option.

If this option is not specified, the latest version is always used. This is
equivalent to specifying a constraint of «>= 0».

The box version configuration can be a specific version or a constraint of
versions. Constraints can be any combination of the following:
, , , , , . You can combine multiple
constraints by separating them with commas. All the constraints should be
self explanatory except perhaps for , known as the «pessimistic constraint».
Examples explain it best: is equivalent to . And
is equivalent to .

You can choose to handle versions however you see fit. However, many boxes
in the public catalog follow semantic versioning.
Basically, only the first number (the «major version») breaks backwards
compatibility. In terms of Vagrant boxes, this means that any software that
runs in version «1.1.5» of a box should work in «1.2» and «1.4.5» and so on,
but «2.0» might introduce big changes that break your software. By following
this convention, the best constraint is because you know it is safe
no matter what version is in that range.

Please note that, while the semantic versioning specification allows for
more than three points and pre-release or beta versions, Vagrant boxes must be
of the format where , , and are all positive integers.

vagrant, VBox и сеть

Private network

С частной сетью понятно — мы делаем собственную сеть LAN, которая будет состоять из виртуальных машин.
Для доступа к такой сети из хоста нужна пробрасывать порт через Vagrantfile (или через Vbox, но через vagrant удобнее).
А для доступа из реальной сети, то есть, например из другой физической машины, мы должны будем стучаться на IP хоста.

Это удобно, если создавать виртуалку для «поиграться» или если планируется использовать виртуалку внутри сети и за NAT (например, она получит адрес от DHCP другой виртуалки, которая будет выполнять роль шлюза).

сконфигурировать можно в Vagrantfile следующим способом:

config.vm.network "private_network", ip xxx.xxx.xxx.xxx

IP можно не указывать, можно сделать так:

config.vm.network "private_network", type: "dhcp"

и адрес назначится автоматически.

Public network

Публичная сеть позволяет добавить машину в вашу подсеть так, как будто появилась дополнительная железная машина.
С публичной сетью нет необходимости пробрасывать порты — всё доступно по адресу виртуалки. Для всех машин в этой же подсети.

Тут надо быть осторожным, если вы не администратор сети. Так как
в подсеть включится новая машина со своим адресом и именем, это может создать
некоторые проблемы с DNS и\или DHCP на основном шлюзе.

Создать публичную сеть можно так:

config.vm.network "public_network", ip: "192.168.1.100"

Если не задать адрес, то он будет задан dhcp-сервером в реальной подсети.
По факту, публичная сеть использует bridge-соединение с WAN-адаптером хоста.
Если у вас два физических адаптера (две сетевых карты, например проводная и беспроводная), то vagrant спросит, какую из них использовать.
В случае, если у вас два адаптера, то вы можете указать его:

config.vm.network "public_network", bridge: "eth1" 

Port Forwarding

Как уже упоминалось выше, vagrant сам пробрасывает 22 порт гостя на 2222 порт
хоста для первой машины.
Для следующих машин это будет 2200, 2300 — называется эта штука auto_correct
Простыми словами — если у вас где-то есть конфликт портов(пробросили на уже
занятый порт), то vagrant это дело увидит и сам исправит, радостно сообщив о
сделанном в консоли.

Автоматически эта опция включена только для 22 порта, для портов, которые вы
задаёте вручну, нужно указать эту опцию как

auto_correct: true

Где? возле каждого порта, который вы указали (пример ниже)

Для того, чтоб принудительно открыть порты, используется следующий синтаксис:

config.vm.network  "forwarded_port", guest: 80, host: 9999, auto_correct: true

в этом примере мы перенаправили стандартный 80 порт для веб-серверов (http) с гостя
на 9999 порт хоста.
Теперь, если у нас в виртуальной машине есть какой-либо веб-сервер (nginx,
apache), то мы сможем попасть на него с хоста двумя способами:

Это возможно благодаря тому, что по-умолчанию vagrant привязывает проброшеный
порт на все доступные в хостовой системе интерфейсы.
Если вы не хотите пробрасывать порт на WAN -интерфейс, то можете конкретно
указать, на какой ip адрес привязать пробощеный порт:

config.vm.network  "forwarded_port", guest: 8080, host: 9898, host_ip: 127.0.0.1 

Если нам требуется пробросить несколько портов, то просто задаём две строки в
Vagrantfile:

config.vm.network  "forwarded_port", guest: 80, host: 9999
config.vm.network  "forwarded_port", guest: 8080, host: 9898

И второй порт тоже будет доступен на хосте.

Никогда не назначайте проброс портов на стандартные! (например,
22 на 22)
Иначе можно огрести неплохих проблем на хостовой машине!

По-умолчанию проброс идёт ТСР протокола, для того, чтоб проборосить UDP порт,
это нужно явно указать:

config.vm.network "forwarded_port", guest: 35555, host: 12003, protocol: "udp" 

»VBoxManage Customizations

VBoxManage is a utility that can
be used to make modifications to VirtualBox virtual machines from the command
line.

Vagrant exposes a way to call any command against VBoxManage just prior
to booting the machine:

In the example above, the VM is modified to have a host CPU execution
cap of 50%, meaning that no matter how much CPU is used in the VM, no
more than 50% would be used on your own host machine. Some details:

  • The special parameter is replaced with the ID of the virtual
    machine being created, so when a VBoxManage command requires an ID, you
    can pass this special parameter.

  • Multiple directives can be used. They will be executed in the
    order given.

There are some convenience shortcuts for memory and CPU settings:

Что такое Vagrant?

Vagrant это инструмент, позволяющий унифицировать среду разработки и среду в которой этот код будет разворачиваться, используя технологию виртуализации. Проще говоря, если вы как и я любитель делать проекты в среде Windows, но в будущем разворачивать их на *nix машинах, то Vagrant вам в помощь 🙂 Очень часто возникают проблемы на фоне того, что среда разработки значительно отличается от среды, где будет крутиться конечное приложение. Например, в Windows название папки с Заглавной буквы и со строчной это одно и то же, хотя в unix системах это две разные папки.

С высоты птичьего полёта, Vagrant ничто иное как CLI (интерфейс командной строки) для VirtualBox с блекджеком и Vagrantfile.

В качестве демонстрационного примера мы создадим изолированную операционную систему на базе Ubuntu 14.04.3 LTS с виртуальным окружением Python + работающим Django приложением внутри.

Терминология

  • Виртуальная ОС — изолированная операционная система, работающая внутри программы-эмулятора
  • Программа-эмулятор — программа, использующая аппаратные средства виртуализации компьютерного процессора (прим. VirtualBox, VMWare, Parallels Desktop и т.д.) для создания изолированных виртуальных операционных систем внутри 1 физической машины
  • Vagrant — программа-обёртка вокруг программы-эмулятора «с плюшками»
  • Vagrantfile — файл, описывающий характеристики и поведение будущей виртуальной операционной системы на языке программирования Ruby

»Windows Access

Working within the WSL provides a layer of isolation from the actual
Windows system. In most cases Vagrant will need access to the actual
Windows system to function correctly. As most Vagrant providers will
need to be installed on Windows directly (not within the WSL) Vagrant
will require Windows access. Access to the Windows system is controlled
via an environment variable: . If
this environment variable is set, Vagrant will access the Windows system
to run executables and enable things like synced folders. When running
in a bash shell within WSL, the environment variable can be setup like so:

This will enable Vagrant to access the Windows system outside of the
WSL and properly interact with Windows executables. This will automatically
modify the environment variable if it is not already defined,
setting it to be within the user’s home directory on Windows.

It is important to note that paths shared with the Windows system will
not have Linux permissions enforced. For example, when a directory within
the WSL is synced to a guest using the VirtualBox provider, any local
permissions defined on that directory (or its contents) will not be
visible from the guest. Likewise, any files created from the guest within
the synced folder will be world readable/writeable in WSL.

Other useful WSL related environment variables:

  • — Override current Windows username
  • — Do not modify the variable
  • — Custom Windows system home path

If a Vagrant project directory is not within the user’s home directory on the
Windows system, certain actions that include permission checks may fail (like
). When accessing Vagrant projects outside the WSL Vagrant will
skip these permission checks when the project path is within the path defined
in the environment variable. For
example, if a user wants to run a Vagrant project from the WSL that is located
at :

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector