in Developer Tools

How to Automatically Add Hosts to Vagrant Without a Password on OS X

UPDATE 2016-07-27: I do not believe this is working with the current version of vagrant-hostmanager 1.2.0. Will update if I find a resolution.

There’s an excellent plugin for vagrant called vagrant-hostmanager which will automatically add entries to your hosts file for domain aliases used in your vagrant instance. However, you’ll get a password prompt every time it runs as editing /etc/hosts requires elevated privileges. The instructions below allow you to run the hostupdater without having to enter your password every time.

The vagrant-hostmanager repo provides these instructions, but I’ve added additional information if you haven’t dealt with visudo before.

Be super careful when editing the sudoers file because editing it incorrectly can lock you out of your computer and prevent you from editing files!

  • Open Terminal
  • Check your $EDITOR env variable: echo $EDITOR
  • If it’s subl -w (for Sublime users) or anything that’s not nano, vi, or vim, you will need to use the longer version of the command below.
  • Short Version: sudo visudo
  • Long Version: sudo EDITOR=nano visudo
  • This opens the sudoers file for editing, which should look like this: http://opensource.apple.com/source/sudo/sudo-60/src/sudoers
  • If the file opens in Sublime Text or is empty, stop what you’re doing, otherwise proceed.
  • Near the bottom of the file, add these two lines, replacing <YOUR_USERNAME> with your OS X username:
Cmnd_Alias VAGRANT_HOSTMANAGER_UPDATE = /bin/cp /home/<YOUR_USERNAME>/.vagrant.d/tmp/hosts.local /etc/hosts
%sudo ALL=(root) NOPASSWD: VAGRANT_HOSTMANAGER_UPDATE

The next time you vagrant up or vagrant halt you shouldn’t be asked to provide your password. It will work for both command line vagrant use and a tool like Vagrant Manager.

Write a Comment

Comment