Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to copy a single file from host to Vagrant guest?

Tags:

vagrant

Since you ask for the easiest way, I suggest using vagrant-scp. It adds a scp command to vagrant, so you can copy files to your VM like you would normally do with scp.

Install via:

vagrant plugin install vagrant-scp

Use it like so:

vagrant scp <some_local_file_or_dir> [vm_name]:<somewhere_on_the_vm>

There is actually a much simpler solution. See https://gist.github.com/colindean/5213685/#comment-882885:

"please note that unless you specifically want scp for some reason, the easiest way to transfer files from the host to the VM is to just put them in the same directory as the Vagrantfile - that directory is automatically mounted under /vagrant in the VM so you can copy or use them directly from the VM."


Instead of using a shell provisioner to copy the file, you can also use a Vagrant file provisioner.

Provisioner name: "file"

The file provisioner allows you to upload a file from the host machine to the guest machine.

Vagrant.configure("2") do |config|
  # ... other configuration

  config.vm.provision "file", source: "~/.gitconfig", destination: ".gitconfig"
end

As default, the first vagrant instance use ssh port as 2222, and its ip address is 127.0.0.1 (You may need adjust the port with real virtual host)

==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (adapter 1)

So you can run below command to copy your local file to vagrant instance. password is the same as username which is vagrant.

scp -P 2222 your_file [email protected]:.

You can also copy the file back to your local host.

scp -P 2222 [email protected]:/PATH/filename .

Here is my approach to the problem:

Step 1 - Find the private key, ssh port and IP:

root@vivi:/opt/boxes/jessie# vagrant ssh-config
Host default
  HostName 127.0.0.1
  User vagrant
  Port 2222
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile /root/.vagrant.d/insecure_private_key
  IdentitiesOnly yes
  LogLevel FATAL

Step 2 - Transfer file using the port and private key as parameters for scp:

  scp -P 2222 -i /root/.vagrant.d/insecure_private_key \
  someFileName.txt [email protected]:~

I hope it helps,


vagrant upload localfile

that will put localfile in the vagrant user's home dir

https://www.vagrantup.com/docs/cli/upload.html


What I ended up doing was to keep the file within my vagrant directory (automatically mounted as /vagrant/) and copy it over with a shell provisioner:

command = "cp #{File.join('/vagrant/', path_within_repo)} #{remote_file}"
config.vm.provision :shell, :inline => command