Can I make Vagrantfile strip whitespace in usernames?

I would like my Vagrantfile to incorporate the name of the user plus the current date. eg:

# -*- mode: ruby -*-
# vi: set ft=ruby :    

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 = "bento/ubuntu-20.04"
      config.vm.hostname = "#{myhostname}"

    (etc)

This generally works fine EXCEPT I didn’t realize that Windows lets usernames contain whitespaces! In these instances, ‘vagrant up’ fails with “the hostname should only contain letters, numbers, hyphens or dots.”

It would be easy to filter the whitespaces with sed, but how can I make it work on a Windows host?

Hi there,

You can remove the whitespace from the hostname value by applying a simple regular expression for replacement:

config.vm.hostname = "#{myhostname.gsub(/\s/, "")}"

This will replace any space characters in the value with nothing (essentially it removes all spaces).

Thanks! It works now, though weirdly it creates the VM with a space in the name (but without an error).

Moving the gsub to the line where myhostname is defined does what I wanted:

myhostname = "#{username.gsub(/\s/, "-")}-linux-vm-#{myDate}"

and then

config.vm.hostname = "#{myhostname}"

like it was before.

thanks again !!