Creating machine name with a variable

18 views
Skip to first unread message

Luke Jaeger

unread,
Apr 7, 2020, 12:48:31 PM4/7/20
to Vagrant
I'm trying to set up my Vagrantfile so that it appends the current date and time to the hostname.
This works on Mac OS but not on Windows. Is there some other way for me to do this?
thanks!

########

# -*- 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.

## THIS IS THE VAGRANTFILE FOR GENERIC 'my-linux-vm'

username = `whoami`.chomp # you need chomp as the result of the command executed this way returns \n at the end
myDate = `date +%Y-%m-%d-%H.%M.%S`.chomp
myhostname = "#{username}-linux-vm-#{myDate}"
Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/bionic64"
  config.vm.provision :shell, path: "install-extras.sh"
  
  # this works:
  config.vm.hostname = "#{myhostname}"
  
  config.vm.provider "virtualbox" do |v|
    v.name = "#{myhostname}"
  end

  config.trigger.after :up  do |updatePkgs|
  updatePkgs.warn = "Checking for software updates"
  updatePkgs.run_remote = {inline: "apt-get --with-new-pkgs upgrade -y"}
  end

  config.vm.synced_folder "./shared", "/shared", create: true

end

Vagrantfile

Jeff Bonhag

unread,
Apr 7, 2020, 3:53:35 PM4/7/20
to vagra...@googlegroups.com
Hi there,

Rather than shelling out to command line tools to get those values, you can use some built-in Ruby functions to achieve the same result. That will make your Vagrantfile a little more cross-platform compatible.

Try something like this:

  require 'date'

  username = ENV['USERNAME'] || ENV['USER']
  myDate = DateTime.now.strftime('%Y-%m-%d-%H.%M.%S')

  myhostname = "#{username}-linux-vm-#{myDate}"

  Vagrant.configure("2") do |config|
    config.vm.box = "ubuntu/bionic64"
    config.vm.hostname = "#{myhostname}"
  end

Cheers,
Jeff


--
This mailing list is governed under the HashiCorp Community Guidelines - https://www.hashicorp.com/community-guidelines.html. Behavior in violation of those guidelines may result in your removal from this mailing list.
 
GitHub Issues: https://github.com/mitchellh/vagrant/issues
IRC: #vagrant on Freenode
---
You received this message because you are subscribed to the Google Groups "Vagrant" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vagrant-up+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/vagrant-up/b0d1b441-5c01-4d1b-aba9-bed267af120b%40googlegroups.com.

Luke Jaeger

unread,
Apr 8, 2020, 10:37:27 AM4/8/20
to vagra...@googlegroups.com, Jeff Bonhag
Reply all
Reply to author
Forward
0 new messages