First Steps with Vagrant

First Steps with Vagrant

Vagrant allows you to easily manage and control multiple virtual machines. It is built on top of VirtualBox and VMWare and it provides many exciting capabilities. You can create isolated development environments, experiment with new products and technologies, install new versions of existing packages, create your own private data center on your laptop and run different operating systems. All that is available in an easy to manage and totally safe silo that can’t interfere with your main activities and operating system. In this article I’ll show you how to set up Vagrant and start exploring the wealth of opportunities it affords.

Installation

Download the free VirtualBox for your operating system from here:

https://www.virtualbox.org/wiki/Downloads

After download, just run the binary and install it.

Download Vagrant itself from here:

http://www.vagrantup.com/downloads

Again, just run the binary to install it.

Initializing Vagrant

Vagrant is a command-line based tool. Once installation is out of the way drop, into your command line prompt and create a new directory (I called mine ‘playground’).

cd ~mkdir playgroundcd playground

Once you’re inside the playground directory type:

vagrant init ubuntu/trusty64

You should see the following text:

A 'Vagrantfile' has been placed in this directory. You are nowready to 'vagrant up' your first virtual environment! Please readthe comments in the Vagrantfile as well as documentation on'vagrantup.com' for more information on using Vagrant. 

The generated ‘Vagrantfile’ is a Ruby file that controls your one or more virtual machines. It is a pretty big file with lots of commented out options. We will ignore it for a moment and just jump with both feet and type:

vagrant up

This will cause Vagrant to download a prepared virtual box with the 64-bit Ubuntu 14.04 (trusty) release. It will take a while and spit a bunch of mumbo jumbo to your screen, so let’s take the time to discuss how to treat your VM.

You may think about the VM as a completely separate server running somewhere. This is a totally valid view and it means that you will interact with the VM through a network interface.

An alternative view is to consider it as a close neighbor with whom you want to exchange information. You will use a synced folder to read and write files on the VM as if they were local files. The fact that the VM really is located on the same machine helps the illusion as there is not a lot of latency as when dealing with a machine that is actually remote.

You can, of course, use both synched folders and still SSH into your VM. There are other options that blur the borders such as port mapping.

The Vagrantfile

Here is a stripped down version of the Vagrantfile with some of the most important options:

Vagrant.configure(2) do |config|config.vm.box = "ubuntu/trusty64"config.vm.network "forwarded_port", guest: 80, host: 8080config.vm.network "private_network", ip: "192.168.33.33"config.vm.synced_folder "../data", "/vagrant_data"machine.vm.hostname = "gigi.playground.local"

The syntax is Ruby, which gives you a lot of flexibility if you want to add conditionals and loops.

I’m Going In?

You can connect to your running VM by typing:

vagrant ssh

This will launch an SSH session and let you fiddle with your VM interactively.

http://i.imgur.com/rVFoVDd.png

Once, inside your VM you can pretty much do anything you want: run commands, create users, create files and directories, etc. You are logged in as the ‘vagrant’ user, which has sudo privileges, so you has full control over the VM.

Exchanging Data with Your VM

Vagrant automatically maps the folder on the host machine that contains the Vagrantfile to the /vagrant directory inside the guest machine. This lets you edit files in your favorite editor on the host machine and have it available in the guest or alternatively have the guest write some output file to the /vagrant directory and browse the synced folder on the host.

Mapping Guest Ports

Often you would run some application that communicates through a port. The most common one is a web server. Vagrant allows you to forward guest ports to the host machine. For example in the configuration above the guest port 80 is mapped to the host 8080 port. What that means is that whatever service is running on port 80 in the guest can be accessed as localhost:8080 in the host machine. Let’s see a demonstration. First, I’ll put a simple index.html file in the ~/playground directory on the host that is synced with the /vagrant directory on the guest

Vagrant is awesome!

Then, after I SSH into the guest machine, I’ll run a little web server in the /vagrant dir:

vagrant@vagrant-ubuntu-trusty-64:/vagrant$ sudo python3 -m http.server 80Serving HTTP on 0.0.0.0 port 80 ... 

This one-liner Python HTTP server simply serves any static file in its working directory. Now, since port 80 is mapped to the host’s 8080 port you can browse to localhost:8080 and view the awesomeness that is Vagrant:

http://i.imgur.com/aZ50LYw.png

Connecting to the VM Through the Network

You can also connect to the VM through its IP address as if it’s a really separate server. This is very useful when testing distributed systems and using a Vagrant VM to simulate a remote server. In this case, the programs that usually connect to the remote server are configured with the VM IP address or hostname. Prior to Vagrant 1.7 there was a single private key that could be used for all machines. This was a serious security problem when people exposed their virtual machine over public networks and anyone could SSH in and get root access. Starting with version 1.7 Vagrant generates a fresh key pair for each machine. To find out where the private key for your machine is run this command:

'vagrant ssh-config'

Here is how you can SSH directly to the VM:

ssh -o UserKnownHostsFile=/dev/null -o CheckHostIP=no -o StrictHostKeyChecking=no -i ~/playground/.vagrant/machines/default/virtualbox/private_key [email protected]

Managing Your Virtual Box

Vagrant provides many commands to manage boxes. You can halt, resume, suspend, stop and even destroy a box. The reload command is good when you make changes to the Vagrantfile. You are always in control. The status command will give you a sense of the current state of your virtual machines (especially useful when managing multiple ones). The global-status command will show all the VMs including those defined in other directories in their own Vagrantfile.

Conclusion

Vagrant gives you an easy to use computer within computer. You can manage a fleet of VMs for diverse purposes and the Vagrantfile is your interface for specifying how the VM should behave. Have fun exploring Vagrant. I just scratched the surface here.

?

Related articles:

Explore Advanced Vagrant Features

devx-admin

devx-admin

Share the Post:
5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within the South Korean market. Many

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles (EVs) after just one day,

Electric Spare

Electric Cars Ditch Spare Tires for Efficiency

Ira Newlander from West Los Angeles is thinking about trading in his old Ford Explorer for a contemporary hybrid or electric vehicle. However, he has observed that the majority of

Solar Geoengineering Impacts

Unraveling Solar Geoengineering’s Hidden Impacts

As we continue to face the repercussions of climate change, scientists and experts seek innovative ways to mitigate its impacts. Solar geoengineering (SG), a technique involving the distribution of aerosols

Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations with industry professionals. The gathering,

Import Easing

Easing Import Rules for Big Tech

India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and Dell Technologies Inc. more time