Search code examples
vagrantvagrantfilevagrant-provision

Passing the host's current user to to vagrant shell provisioner


I want to pass the current user within my Vagrantfile, but I'm not sure how to do it.

I've tried this:

config.vm.provision :shell, inline: "echo $(whoami) > /etc/profile.d/me"

But it results in 'root' being put into the file, which I assume is the vagrant host's user. I want to get the username for the host.


Solution

  • That's because your inline shell script runs inside the vagrant box.

    You can do it like this:

    Get username from host depending on platform (you can simplify this if you never expect a windows host).

    @host_user = Gem.win_platform? ? "#{ENV['USERNAME']}" : "#{ENV['USER']}"
    

    Pass the username from the host as environment variable during the provisioning and use it in an inline script.

    config.vm.provision "Passing host username as env var...", type: :shell, inline: $hostUser, env: {"HOST_USER" => "#{@host_user}"}
    

    Add this outside the ruby part, it gets then run by the code above and appends the username which got passed as environment variable to the file you specified:

    $hostUser = <<-SET_HOST_USER
    echo "$HOST_USER" > /etc/profile.d/me"
    SET_HOST_USER