You are on page 1of 70

Study Guide

Learning Vagrant

Elle Krout
elle@linuxacademy.com
Oct 15, 2019
Study Guide | Learning Vagrant

Contents

What Is Virtualization? 9

Overview 9

Why Virtualize? 9

What Is a Hypervisor 11

Overview 11

Vagrant Support 11

What Is Vagrant? 13

Overview 13

Vagrant Components 13

Our Environments 15

2
Study Guide | Learning Vagrant

Linux 16

Vagrant 16

VirtualBox 16

Mac 17

Vagrant 17

VirtualBox 17

Windows 18

Git 18

Vagrant 18

VirtualBox 19

Plugin Overview 20

Updating: 20

Provider Plugins 22

3
Study Guide | Learning Vagrant

Additional Plugins 23

Boxes 24

Discover Boxes 24

The Vagrantfile 25

The Simplest Possible Vagrantfile 25

Vagrant Up 27

Accessing the VM 29

VM Management 30

Snapshots 31

save and restore 31

push and pop 32

4
Study Guide | Learning Vagrant

Basic Syncing 33

Options 33

Example Vagrantfile 34

NFS 35

RSync 36

SMB 38

Port Management 39

Working with Multiple Machines 40

Public Networking 43

Provisioning Overview 44

Shell 45

5
Study Guide | Learning Vagrant

File 47

Ansible 48

Ansible Provisioner 48

Ansible Local 49

Ansible Common 49

Chef 51

Chef Solo 51

Chef Zero 52

Chef Client 53

Chef Apply 53

Common Configuration Options 54

Puppet 55

Puppet Apply 55

Puppet Agent 56

6
Study Guide | Learning Vagrant

Salt 57

Docker 59

Box Overview 60

The Box File 61

Packaging an Existing Machine 62

Creating a Base Box 63

Share Overview 65

HTTP Sharing 66

SSH Sharing 67

Vagrant Connect 68

Windows Considerations 69

7
Study Guide | Learning Vagrant

Tools and Scripting 70

8
Study Guide | Learning Vagrant

What Is Virtualization?

Overview
• The act of creating a "virtual" (non-real) version of something
• Hardware virtualization:
• Creates a "virtual" computer ("virtual machine") on top of an existing computer
• Uses the existing machine's hardware:
CPU, RAM, disk space
• Uses its own operating system
• Virtual machines created/managed by a control program, called a hypervisor
• Hypervisor examples:
• KVM
• XEN
• VMware
• VirtualBox
• Parallels

Why Virtualize?
• Datacenter hardware is often too large for most needs:
• Divides the host into smaller virtual machines

9
Study Guide | Learning Vagrant

• Commonly used by:


Cloud platforms
Large organizations that need to tightly control their data
• Development environments allow administrators, engineers, and developers access to replica environments for
testing code:
• Creates a smaller, virtualized machine on the user's workstation computer
• Commonly used by:
Anyone who doesn't want to work on production

10
Study Guide | Learning Vagrant

What Is a Hypervisor

Overview
• The process, software, firmware, or hardware that creates a virtual machine
• Exists only to let virtual machines share resources with the host
• Abstracts resources from the guest machine
• Two types of hypervisors for two circumstances:
• Type I hypervisors work on bare metal
• Type II hypervisors work over an operating system
• For some hypervisors, this distinction is less clear
KVM, which is a Linux kernel module, can be classified as both a type I and II hypervisor

Vagrant Support
• Native hypervisor support:
• VirtualBox
• Hyper-V
• Docker*
• Additional hypervisors can be added through the use of provider plugins:
• A provider is the underlying platform that creates our virtual machines:
Most often a hypervisor, but can also be containers or the cloud

11
Study Guide | Learning Vagrant

Docker is not a hypervisor but a containers platform; support for Docker was added in Vagrant 1.6. Note that not all Vagrant
features can be used with the Docker provider.

12
Study Guide | Learning Vagrant

What Is Vagrant?

Overview
• Vagrant is not a hypervisor.
• Vagrant is not a virtualization platform.
• Vagrant is a wrapper tool that allows us to automate our virtual machine workflow to create easy-to-use and easy-
to-replicate environments.
• Vagrant leverages an existing hypervisor (or container/cloud platform) to create virtual machines.

Vagrant Components
• The Vagrantfile:
• The file that describes the environment we wish to provision
• Written in Ruby
• Boxes:
• The base image used to provision the guest server(s)
• Can be taken from app.vagrantup.com or self-made
• The CLI:
• The command line interface used to manage Vagrant environments
• Plugins:
• Any assisting feature or functionality added to Vagrant:
Providers are a plugin

13
Study Guide | Learning Vagrant

VirtualBox Guest Additions support is a plugin


Provisioner (Chef, Puppet, etc.) support is a plugin

14
Study Guide | Learning Vagrant

Our Environments

• For videos:
• Personal workstation (not Cloud Playground)
• VirtualBox
• Vagrant
• Ubuntu 18.04 guest
• For hands-on labs:
• EC2 instance
• LXC or Docker
• Vagrant
• Various guests

15
Study Guide | Learning Vagrant

Linux

Vagrant
• Download from the Download Vagrant page:
• Previous versions found here
• This course uses Vagrant 2.2.5
• Verify the checksum before download:
• Signature file is found on downloads page, as well as included in the directory for any previous releases
• Extract using appropriate system package manager:
• .zip file for non Debian/CentOS-based hosts, requires manual install

VirtualBox
• Download the appropriate package for your distro at the Linux Downloads page:
• This course uses version 6.0.10
• Import Oracle's public key to validate the download
• Extract using either rpm , dpkg , or by following the instructions on the download page

16
Study Guide | Learning Vagrant

Mac

Vagrant
• Download from the Download Vagrant page:
• Previous versions found here
• This course uses Vagrant 2.2.5
• Double click the .dmg file to open
• Double click vagrant.pkg to start the installer
• Follow the installer:
• Select the installation location
• Click Install

VirtualBox
• Download the "OS X hosts" option from the VirtualBox Downloads page:
• This course uses version 6.0.10
• Double click the .dmg file to open
• Double click the VirtualBox.pkg icon
• Follow the installer:
• Select the installation location
• Click Install

17
Study Guide | Learning Vagrant

Windows

Git
• Download Git for Windows from the Git download page:
• This course uses version 2.22.0
• Open the downloaded .exe file
• Follow the prompts to install:
• Select Git from the command line and also from 3rd-party software
• Select Use the OpenSSL library
• Select Checkout as-is, commit Unix-style line endings
• Select Use MinTTY

Vagrant
• Download Vagrant for Windows from the Vagrant Downloads page:
• This course uses version 2.2.5
• Open the downloaded .msi file
• Follow the prompts to install:
• Wait to restart until after VirtualBox is installed

18
Study Guide | Learning Vagrant

VirtualBox
Note: that if you are already using Hyper-V, it must be disabled before you can use VirtualBox

• Download VirtualBox for Windows Hosts from the Download VirtualBox page:
• This course uses version 6.0.10
• Open the downloaded .exe file
• Follow the prompts to install:
• Note that you will temporarily be disconnected from the Internet
• To finish, restart your Windows machine
• To test Vagrant, open the Command Prompt ( cmd.exe ):
• Run vagrant version to confirm

19
Study Guide | Learning Vagrant

Plugin Overview

• Takes only a single command:


• vagrant plugin install PLUGIN
• Most plugins are third-party:
• All the risks of third-party tooling
• Written by non-core users
• Not guaranteed to be updated/maintained
• Plugins can be used immediately after download
• Always read documentation before downloading

Updating:
• All plugins:
• vagrant plugin update
• A single plugin:
• vagrant plugin update PLUGIN
• Repair failing plugins:
• vagrant plugin repair
• Install license for proprietary plugin: vagrant plugin license LICENSE-FILE
• Uninstall:
• vagrant plugin uninstall PLUGIN

20
Study Guide | Learning Vagrant

• Remove all plugins, dependencies, and metadata:


• vagrant plugin expunge
• Reinstall expunged plugins:
vagrant plugin expunge --reinstall
Good for upgrading Vagrant

21
Study Guide | Learning Vagrant

Provider Plugins

• Plugins are how we add additional provider support


• There are several providers to choose from:
• Hypervisors
• Cloud hosts
• Containers
• Additional virtualization tools
• Providers are managed the same way as regular plugins
• Thirty-four provider plugins at time of writing
• Most are thirty-party providers:
• Same warnings as previous lesson
• Sometimes there are duplicates (i.e., two OpenStack providers)
• A full list can be found here

22
Study Guide | Learning Vagrant

Additional Plugins

• Some quality-of-life plugins for making this course go smoothly:


• vagrant-vbguest
• vagrant-winnfsd (Windows only, NFS support)
• Nice to have (but not neccessary) plugins:
• vagrant-hostmanager
• vagrant-git
• A full list of plugins is here

23
Study Guide | Learning Vagrant

Boxes

• A box is a "golden image" that packages the Vagrant environment:


• Can be simple, base boxes with just the operating system
• Can be more complicated images, such as a LAMP stack or Python development environment

Discover Boxes
• Boxes can be user-created or downloaded from other parties
• The official box repository can be found here
• Hashicorp only offers a few Ubuntu-based boxes
• Namespaces do not mean the box is official
• HashiCorp also recommends Bento, which provides open source boxes that work across multiple hypervisors
• Add a box:
• vagrant box add USER/BOX

24
Study Guide | Learning Vagrant

The Vagrantfile

• Describe the desired type of machine:


• How to provision
• How to configure
• Literally named Vagrantfile in project directory:
• Case does not matter
• Written in Ruby:
• Ruby knowledge not necessary:
Variable assignment
Simple loops and statements

The Simplest Possible Vagrantfile


• Generate a documented Vagrantfile in the current directory:
• vagrant init
• Line breakdown:
• Vagrant.configure("2") do |config| :
Sets the version of Vagrant used. Versions are backwards-compatible
All Vagrant configuration is done in this function
• config.vm.box = "base"
config references the configuration version line ( ... do |config| )

25
Study Guide | Learning Vagrant

vm modifies a virtual machine setting


box is part of the overall vm namespace and defines which box we want to use
• end
Ends the function

• The file without commentary:

Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/bionic64"
end

• Validate the file:


• vagrant validate :
Runs in the same directory as the Vagrantfile
Looks for syntax errors

26
Study Guide | Learning Vagrant

Vagrant Up

• Run vagrant up to deploy an environment


• What happens when a vagrant up occurs?
• Vagrant loads the Vagrantfiles
Looks for:
The Vagrantfile in the current directory
Looks up the directory structure until it is found; ex:
/home/cloud_user/projects/ubuntu/Vagrantfile
/home/cloud_user/projects/Vagrantfile
/home/cloud_user/Vagrantfile
/home/Vagrantfile
/Vagrantfile
Multiple Vagrantfiles, in this order:
The Vagrantfile packaged with the defined box
The Vagrantfile in the user's home directory ( ~/.vagrant.d )
The Vagrantfile in the project directory
Multi-machine overrides
Provider-specific overrides
New layers override the old:
Networks are appended

27
Study Guide | Learning Vagrant

No Vagrantfile for that layer? Move to the next

28
Study Guide | Learning Vagrant

Accessing the VM

• Access host:
• vagrant ssh <hostname>
• Access from outside of the environment directory:
• vagrant ssh-config
• --host to define a specific host
• Default user:
• vagrant
• Has superuser privileges
• Logs in with a private key
Stored in hidden .vagrant directory

29
Study Guide | Learning Vagrant

VM Management

• View status of current VM environment:


• vagrant status
• View status of all machines:
• vagrant global-status
• Remove old entries:
vagrant global-status --prune
• Shut down running VM(s):
• vagrant halt
• Perform a graceful shutdown ( halt ), then start the machine ( up ):
• vagrant reload
• The equivalent to a vagrant halt followed by a vagrant up
• Suspend machine in current state (not a proper shutdown):
• vagrant suspend
• Takes up more disk space
• Machine resumes at exact point in time it was stopped
• Resume suspended machines:
• vagrant resume
• Delete virtual machine(s):
• vagrant destroy

30
Study Guide | Learning Vagrant

Snapshots

• Point-in-time images of the guest machine(s)


• Use to restore to the snapshot environment
• Not supported by every provider
• Two methods of using snapshots:
• push and pop
• save and restore
• The two methods cannot be used together
• Snapshots are destroyed with vagrant destroy

save and restore


• Save a named snapshot:
• vagrant snapshot save [vm] <name>
• List snapshots:
• vagrant snapshot list
• Restore a saved snapshot:
• vagrant snapshot restore [vm] <name>
• Remove snapshot:
• vagrant snapshot delete [vm] <name>

31
Study Guide | Learning Vagrant

push and pop


• Can only store one snapshot at a time
• Save a snapshot:
• vagrant snapshot push
• Works like vagrant snapshot save without identifying a name
• Restore snapshot:
• vagrant snapshot pop
• Snapshot is deleted after restore

32
Study Guide | Learning Vagrant

Basic Syncing

• Upload files manually:


• vagrant upload <source> <destination> [hostname]
• Better to sync needed files between machines automatically:
• Vagrantfile option to sync files:
• config.vm.synced_folder "src", "/var/www/app" :
src should be relative to the directory that the Vagrantfile is in
/var/www/app is the desired destination on the host

Options
• create (boolean): Creates the host path if it does not exist
• group (string): Set group owner of the guest directory
• owner (string): Set owner of the guest directory
• mount_options (array): Any additional mount options we wish to pass
• id (string): The name of the mount point (what shows up when running mount on the guest)
• disabled (boolean): Added to the end of the initial config.vm.synced_folder line; prevents file syncing

33
Study Guide | Learning Vagrant

Example Vagrantfile
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/bionic64"
config.vm.synced_folder "app/", "/var/www/wanderer",
create: true, group: "vagrant", owner: "vagrant", id: "wanderer-app"
end

34
Study Guide | Learning Vagrant

NFS

• Declare the file syncing solution by adding the type option to the config.vm.synced_folder configuration:
• config.vm.synced_folder "app/", "/var/www/app", type: "nfs"
• Host must have NFS installed:
• Host:
Debian: nfs-kernel-server
RedHat: nfs-utils
Mac: Preinstalled
Windows: Add vagrant-winnfsd plugin
• Vagrant can install NFS on some guests, but it may need to be installed
• Cannot use owner / group options
• A static network must be added:
• config.vm.network "private_network", type: "dhcp"
• Additional options:
• nfs_export (boolean): Will assume /etc/export has been updated manually
• nfs_udp (boolean): Determine whether or not to use UPD as the transfer method
• nfs_version (string or integer): The desired NFS protocol

35
Study Guide | Learning Vagrant

RSync

• Switch type to rsync


• Only syncs during vagrant up and vagrant reload :
• Generally used when there are no other options
• Can be forced:
• vagrant rsync
• Enable permanently: vagrant rsync-auto
• The host must have rsync (or rsync.exe ) available on the path
• Vagrant can automatically install rsync on most guests:
• Destination folder will be created by default user ( vagrant )
• Supports all default syncing options
• Additional options:
• rsync__auto (boolean): Watch directories and automatically sync
• rsync__chown (boolean): Set to false to disable group and owner options
• rsync__exclude (string or array of strings): Files and directories to exclude when syncing
• rsync__rsync_ownership (boolean): By default, Vagrant does not use rsync itself to set the user and group
ownership settings. Instead, a separate call is run. If both the host and guest versions of rsync are >= 3.1.0, we
can have rsync set the group permissions by setting this to true .
• rsync__rsync_path (string): The location of the rsync command if outside the default
• rsync__verbose (boolean): Enable verbose output

36
Study Guide | Learning Vagrant

• rsync__args (array of strings): Any additional arguments to pass to rsync

37
Study Guide | Learning Vagrant

SMB

• "Server Message Block"


• Windows and OSX only (host)
• Windows must have PowerShell 3 or later installed
• OSX must have file sharing enabled:
System Preferences - Sharing
Check off the File Sharing option
Click Options
Check off your username
Click Done
• Any OS guests
• Appropriate package installed automatically for some distros
• Additional options:
• smb_host : Defaults to the localhost (for the host); IP address of SMB mount
• smb_password : Password to access SMB mount:
Not recommended
• smb_username : User to access SMB mount

38
Study Guide | Learning Vagrant

Port Management

• config.vm.network option
• "forwarded_port" setting
• Options:
• auto_correct (boolean): Automatically change port if clashing with an existing port
• guest (int): The port on the guest to expose on the host
• guest_ip (string): The guest IP to which to bind
• host (int): The host IP to use; must be greater than 1024
• host_ip (string): The host IP to which to bind
• protocol (string): UDP or TCP
A rule must be added for each protocol
• id (string): Name to call this networking rules
• View mapped ports:
• vagrant port

39
Study Guide | Learning Vagrant

Working with Multiple Machines

• Control multiple machines in a single Vagrantfile


• Machines should be associated with each other in some way:
• Web and database servers
• Use case testing
• Modeling distributed systems

• To add multiple machines, create a " Vagrantfile within a Vagrantfile using config.vm.define " method block:

config.vm.define "app" do |app|


<CONFIGURATION DIRECTIVES FOR APP>
end
config.vm.define "prom" do |prom|
end

• The name defined is the name Vagrant will use for the machine:
• Used for vagrant commands; i.e., vagrant halt app will halt only the app machine

40
Study Guide | Learning Vagrant

• Place configuration blocks in the method for each machine, replacing config with the name assigned to the
machine:

config.vm.define "app" do |app|


app.vm.synced_folder "app/", "/var/www/app",
create: true, group: "vagrant", owner: "vagrant",
id: "app"
app.vm.network "forwarded_port", guest: 8080, host: 8081,
auto_correct: true, id: "wanderer-app"
end

• Anything set with config outside of the block is applied to all machines:
• Code outside of the block is configured first

• Set default machine for CLI:

config.vm.define "app", primary: true do |app|


end

• Prevent machine from autostarting during vagrant up :

config.vm.define "app", autostart: false do |app|


end

41
Study Guide | Learning Vagrant

Private Networking

• Access guest machine at IP address is available only from within the network
• Vagrant configures this automatically based on the Vagrantfile for most systems:
• Exceptionally old/new systems may not have support
• Configure DHCP:
• config.vm.network "private_network", type: "dhcp"
• IP address automatically assigned:
Use auto_config: false to disable
Use ifconfig /related command to discover private IP on guest
• Configure a static IP:
• config.vm.network "private_network", ip: "192.168.50.4"
• User must ensure IP is not already used
• No limitations, but should be in reserved private address space:
10.0.0.0 - 10.255.255.255
172.16.0.0 - 172.31.255.255
192.168.0.0 - 192.168.255.255
IPv6 supported, but not over DHCP:
Uses same ip option
Use auto_config: false to disablelso set the netmask with netmask (default: 64)

42
Study Guide | Learning Vagrant

Public Networking

• The function of public networking depends on the provider


• For VirtualBox, this is creating a bridged network that will allow the greater network access to the host
• Use DHCP to autoconfigure:
• config.vm.network "public_network"
• Options:
• ip (string): Set IP, if permitted
• use_dhcp_assigned_default_route (boolean): Set whether to use the assigned default route
• bridge (string, array): The interface to which to bridge
• auto_config (boolean): Enable/disable auto-configuration of this network

43
Study Guide | Learning Vagrant

Provisioning Overview

• Install software and otherwise configure the guest


• Makes environment repeatable and won't have to be reinstalled after every destroy
• Provisioned only during first vagrant up :
• Use --provision flag to re-provision:
Can be used with up or reload

44
Study Guide | Learning Vagrant

Shell

• Execute a shell script


• Can be inline, embedded in the Vagrantfile, or provided via a path
• Run as vagrant user with sudo privileges
• Inline:
• config.vm.provision "shell", inline: "apt-get install nodejs npm -y"

• Embedded:

$script = <<-SCRIPT
apt-get install nodejs npm -y
useradd --no-create-home --shell /bin/false node_exporter
...
SCRIPT

...
Vagrant.configure("2") do |config|
config.vm.provision "shell", inline: $script
end

• Path:
• config.vm.provision "shell", path: "script.sh"
• Useful options:
• privileged (boolean): Run script with elevated privileges; defaults to true

45
Study Guide | Learning Vagrant

• reboot (boolean): Reboot guest when finished


• env (hash): List of key-value pairs to pass into the script

46
Study Guide | Learning Vagrant

File

• Upload file or directory to host:


• Not sync, just upload
• Good for static configurations, etc.
• Basic file provisioning:
• config.vm.provision "file", source: "~/.vimrc", destination: ".vimrc" :
Can be a file or directory
Does not work with elevated privileges

47
Study Guide | Learning Vagrant

Ansible

• Two options:
• Ansible
• Ansible Local

Ansible Provisioner
• Requires Ansible to be downloaded on the workstation
• Essentially, Vagrant uses Ansible as you would normally use Ansible

• Up and running:

config.vm.provision "ansible" do |ansible|


ansible.playbook = "playbook.yml"
end

• Options:
• ask_become_pass (boolean): Require Ansible to ask for a password prompt when becoming another user or
using sudo
• ask_vault_pass (boolean): Require Ansible to ask for a vault password
• force_remote_user (boolean): When true (default), Vagrant uses the ansible_ssh_user in the inventory as
the Ansible remote user; when set to false, the vagrant user is used
• host_key_checking (boolean): Require SSH host key checking
• raw_ssh_arg (array of strings): Pass in OpenSSH client options

48
Study Guide | Learning Vagrant

Ansible Local
• Does not require Ansible on the host system

• Up and running:

config.vm.provision "ansible_local" do |ansible|


ansible.playbook = "playbook.yml"
end

• Options:
• install (boolean): When set to true (default), attempt to install Ansible on guest system
• install_mode ( default , pip , or pip_args_only ): Determine the installation method; default is the
package manager for the guest
• pip_args (string): Additional arguments if install_mode is set to use pip
• provisioning_path (string): The absolute path on the guest where Ansible files are stored
• tmp_path : The absolute path on the guest where temporary files generated by Ansible Local are stored

Ansible Common
• Additional options for both provisioners, changes the options passed to the ansible-playbook command
• Selected options:
• become (boolean): Run commands as the become_user
• become_user (string): The user to run commands as when become is set to true
• config_file (string): Set Ansible configuration file location
• extra_vars (string or hash): Pass in additional variables (path to JSON/YAML file or hash)
• groups : Set inventory groups for inventory file

49
Study Guide | Learning Vagrant

• inventory_path (string): The location of an inventory file, a script, or a directory


• raw_aguments (array of strings): Additional parameters to feed into the ansible-playbook command
• verbose (boolean): Enable detailed logging
• Additional commands for using Ansible Galaxy and other specific use-cased can be found here

50
Study Guide | Learning Vagrant

Chef

• Four different provisioners:


• Chef Solo
• Chef Zero
• Chef Client
• Chef Apply

Chef Solo
• Uses chef-solo , which executes the Chef client without a Chef server
• Ideal for Chef new people and experts alike

• Up and running:

config.vm.provision "chef_solo" do |chef|


chef.add_recipe "apache"
end

• Options:
• cookbooks_path (string or array): The location of cookbooks
• data_bags_path (string or array): The location of data bags
• environments_path (string): The location of environment definitions
• nodes_path (string or array): The location of JSON node objects
• recipe_url (string): The URL of a cookbook archive

51
Study Guide | Learning Vagrant

• roles_path (string or array): The location of role definitions


• synced_folder_type (string): The type of synced folder protocol to use to share provisioner data; uses the
default synced folder type

Chef Zero
• Uses chef-zero to run in "local mode"
• chef-zero itself acts as a lightweight version of the Chef Infra Server
• Middle ground between Chef Solo and full Chef server

• Up and running:

config.vm.provision "chef_zero" do |chef|


chef.add_recipe "apache"
end

• Options:
• cookbooks_path (string or array): The location of cookbooks
• data_bags_path (string or array): The location of data bags
• environments_path (string): The location of environment definitions
• nodes_path (string or array): The location of JSON node objects
• recipe_url (string): The URL of a cookbook archive
• roles_path (string or array): The location of role definitions
• synced_folder_type (string): The type of synced folder protocol to use to share provisioner data:
Uses the default synced folder type

52
Study Guide | Learning Vagrant

Chef Client
• Use Chef with a Chef Infra Server

• Up and running:

config.vm.provision "chef_client" do |chef|


chef.chef_server_url = "chef.server.internal"
chef.validation_key_path = "validation.pem"
chef.add_recipe "apache"
end

• Options:
• client_key_path : Specify the path to the client key
• validation_client_name : The name of the chef-validator key

Chef Apply
• Use chef-apply , which runs a single recipe from the command line

• Up and running:

config.vm.provision "chef_apply" do |chef|


chef.recipe = "package[apache2]"
end

• Options:
• recipe (string): The raw recipe contents
• upload_path (string): The location on the guest in which the generated recipe file is stored; defaults to /tmp/
vagrant-chef-apply-*

53
Study Guide | Learning Vagrant

Common Configuration Options


• Selected options for all provisioners:
• install (boolean, force ): Install Chef on the system if it is not already installed:
Defaults to true
• log_level (string): The log level to store:
This can vary by provisioner
• product (string): chef or chefdk , for the development kit
• version (string): Version of Chef to use:
Default is "latest"
• Selected options for "runner" provisioners: Chef Solo, Chef Zero, Chef Client
• aurguments (string): Additional arguments to pass on the command line during the provisioning Chef run
• encrypted_data_bag_secret_key_path (string): The path to the secret key file for decrypting encrypted data
bags
• environment (string): The environment that the guest should be part of
• json (hash): Add custom node attributes
• node_name (string): Set node name:
Defaults to hostname
• verbose_logging (boolean): Enable verbose logging
• enable_reporting (boolean): Enable Chef reporting

54
Study Guide | Learning Vagrant

Puppet

• Two Puppet providers:


• Puppet Apply
• Puppet Agent

Puppet Apply
• Use Puppet without a Puppet Master
• Automatically looks for default manifest as manifests/default.rb

• Up and running:

config.vm.provision "puppet"

• Set modules:

config.vm.provision "puppet" do |puppet|


puppet.module_path = "modules"
end

• Selected options:
• facter (hash): Set Facter facts
• hiera_config_path (string): Location of the Hiera configuration of the host
• manifest_file (string): The default manifest file
• manifests_path (string): Location of the manifests directory on the host

55
Study Guide | Learning Vagrant

• module_path (string): Location(s) of the modules directory on the host


• environment (string): Set guest environment
• environment_path (string): Location of environment configurations
• environment_variables (hash): Environment-specific variable definitions
• options (array of strings): Additional options to pass to the puppet command
• synced_folder_type (string): Type of synced folders to use:
Defaults to the provider default

Puppet Agent
• Connect to a Puppet master

• Up and running:

config.vm.provision "puppet_server" do |puppet|


puppet.puppet_server = "puppet.example.com"
end

• Options:
• binary_path (string): Location of Puppet binary on guest
• client_cert_path (string): Location of client certification on host
• client_private_key_path (string): Location of client private key on host
• facter (hash): Additional Facter facts
• options (string or array): Additional command line options to pass to the puppet agent command
• puppet_node (string): Set the node name (Defaults to the hostname)
• puppet_server (string): Hostname of the Puppet server (Defaults to puppet )

56
Study Guide | Learning Vagrant

Salt

• Only one Salt provisioner, set masterless in the Vagrantfile


• Need to create synced folders for Salt formulas, pillar data, etc.
• Up and running:
• Minion configuration needs to be set to file_client: local

config.vm.synced_folder "salt/roots/", "/srv/salt/"


config.vm.provision "salt" do |salt|
salt.masterless = true
salt.minion_config = "salt/minion"
salt.run_highstate = true
end

• Selected options:
• Installation:
install_master (boolean): Install master on guest (not supported on Windows guests)
no_minion (boolean): Do not install minion (not supported on Windows guests)
install_syndic (boolean): Install salt-syndic (not supported on Windows guests)
version (string): Version of Salt to install
• Minion options:
minion_config (string): Path to minion configuration (defaults to salt/minion on the host)
minion_key (string): Path to minion key (defaults to salt/key/minion.key )

57
Study Guide | Learning Vagrant

minion_id (string): Set name of guest in Salt


grains_config (string): Path to custom grains file
masterless (boolean): Run minion without master
• Master options:
master_config (string): Path to master configuration file (defaults to salt/master )
master_key (string): Path to master key (defaults to salt/key/master.pem )
• Other:
run_highstate (boolean): Execute highstate on guest
pillar (hash): Set pillar data
orchestrations (array of strings): Use state.orchestrate on vagrant up (master-only)
log_level (string): Set log level
verbose (boolean): Enable verbose logging

58
Study Guide | Learning Vagrant

Docker

• Unlike the Docker provider, the Docker provisioner installs Docker on a guest VM and runs Docker images on that
guest
• Can be run with no options (this will install Docker)
• Up and running:
• config.vm.provision "docker"
• Options:
• images (array): Images to pull via docker pull
• pull_images (array): Images to pull via docker pull
• post_install_provisioner (method): An additional provisioner block to run after Docker installation
• run : Run a container and configure it to start on boot (can only be specified once):
image (string: Image to run
cmd (string: Command to start within the container
args (string): Additional arguments to pass in the docker run command
daemonize (boolean): Run Docker as a daemon (defaults to true )
auto_assign_name (boolean): Automatically assign the name of the container based on the first argument
of the run
restart : Container restart policy (; defaults to always )
• build_image (string): Location on guest of Dockerfile to build image based on
args (string): Additional arguments to call to build_image

59
Study Guide | Learning Vagrant

Box Overview

• The package format for Vagrant environments


• Managed with vagrant box command
• As of Vagrant 1.5, boxes are versioned:
• View boxes available, with versions:
vagrant box list
• To see all versions, view the Vagrant box repo
• Boxes can be constrained to a certain version
• Enable automatic update checking in Vagrantfile:
config.vm.box_check_update =true
• Check if it's outdated:
vagrant box outdated
Add --global to check all boxes
• Prune old boxes:
vagrant box prune
• Update to new version:
vagrant box update
• Remove a box:
vagrant box remove <box>

60
Study Guide | Learning Vagrant

The Box File


• Boxes are packaged in box format, containing three components:
• The Box file: A compressed file specific to a single provider (this is passed directly to the provider)
• Metadata: A JSON document that specifies the name of a box, its description, version, available providers, and
box URL(s)
• Box information: Additional information formatted as JSON provided during a vagrant box list -i

61
Study Guide | Learning Vagrant

Packaging an Existing Machine

• Take an existing Vagrant box that has been changed and repackage it as a new box
• Package existing guest:
• vagrant package
• Options:
Name of file to output:
--output name.box
Include metadata files:
--include files
Include Vagrantfile:
--vagrantfile file

62
Study Guide | Learning Vagrant

Creating a Base Box

• Provider-dependent, but there are some generalities


• Base box must include:
• Package manager
• SSH
• vagrant SSH user
• Disk space should be dynamically allocated:
• Enough for the user to really be able to test things out
• Memory should be a small amount (512 MB is generally a good place to start)
• Can be changed by the end user in the Vagrantfile
• Disable unneeded peripherals
• User settings:
• root user
Password: vagrant
• vagrant user
Password: vagrant
Passwordless sudo
visudo
Disable requiretty

63
Study Guide | Learning Vagrant

Uses the Vagrant public key (GitHub)


Stored in .ssh/authorized_keys
• Vagrantfile:
• Base MAC address ( config.vm.base_mac )
• Synced vagrant directory ( config.vm.synced_folder ".", "/vagrant" )

64
Study Guide | Learning Vagrant

Share Overview

• Share Vagrant environment with a single command


• Three modes:
• HTTP
• SSH
• "General" or vagrant connect
• Works as a separate plugin:
• Install: vagrant plugin install vagrant-share
• Backed by ngrok, which exposes private networks via secure tunnels to share machines:
• ngrok must be downloaded separately
• Download here
• Security:
• End-to-end TLS for non-HTTP connections
• Encrypted SSH keys
• SSH not used by default (must be shared with --ssh flag)
• "Security through obscurity"

65
Study Guide | Learning Vagrant

HTTP Sharing

• The default mode of sharing


• Creates publicly accessible URL endpoint to HTTP(s) server
• Vagrant does not been to be installed to use URL
• Autodetects forwarded ports
• vagrant share to run:
• Outputs URL
• Use --http or --https (share is unable to determine automatically)
• Quit with CTRL+C
• Applications must use relative paths
• HTTPS requires non-free ngrok

66
Study Guide | Learning Vagrant

SSH Sharing

• Allows for remote SSH access to environment


• Creates new key pair, providing the user with a private key:
• Public key auto-added to guest
• Encrypted with password set by sharer
• Run vagrant share --ssh :
• Outputs name of share in word1_word2:word3_word4 format
• Connect: vagrant connect --ssh word1_word2:word3_word4 :
• Prompted for password set by sharer

67
Study Guide | Learning Vagrant

Vagrant Connect

• Expose all IPs so that they can receive TCP traffic


• Share all ports: vagrant share --full
• Connect to shared machine: vagrant connect <name> :
• Provides IP, can connect at any port

68
Study Guide | Learning Vagrant

Windows Considerations

• Windows often has a host of additional concerns/considerations


• Windows Vagrantfile options:
• config.vm.winrm - Configures access to guest over WinRM
• config.vm.winssh - Configure native OpenSSH support for Windows
• Windows guests can also support:
• vagrant powershell - Opens PowerShell prompts
• vagrant rdp - Starts an RDP client for a remote desktop session with the guest

69
Study Guide | Learning Vagrant

Tools and Scripting

• Further your Vagrant knowledge after this course


• Vagrant Push:
• Push application code to a remote location (FTP server, etc.)
• Provide login information for the remote
• Push using the vagrant push command
• Explore plugin development
• Written in Ruby
• Packaged with RubyGems
• Vagrant's plugin development guide
• Use machine triggers
• Run before or after Vagrant commands:
Save database test information to workstation before a vagrant destroy

70

You might also like