tipotto
tipotto

Reputation: 107

Vagrant cannot find files on Host OS in Vagrantfile

I attempted to reference a file on Host OS in Vagrantfile and set an environment variable.
However, it appears that Vagrant fails to find the file.

Everything works perfectly when the file located in the same directory as Vagrantfile is referenced.

1. Is the files that Vagrant can access in Vagrantfile limited to VM directory?

2. Is it possible to reference files outside of VM directory(test1, test2, test3...) in Vagrantfile? (e.g. /Users/hoge/vagrant/key.json)

My project and Vagrantfile are as follows.

/Users/hoge
  /vagrant
    - key.json

    /test1
      - Vagrantfile
      - provision.sh
      - /workspace

    /test2
      ...

    /test3
      ...

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

Vagrant.configure("2") do |config|

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://vagrantcloud.com/search.
  config.vm.box = "ubuntu/bionic64"

  # Directory ./workspace needs to be made in advance, or error occurs.
  config.vm.synced_folder "./workspace", "/home/vagrant/workspace"

  # Provider-specific configuration so you can fine-tune various
  # backing providers for Vagrant. These expose provider-specific options.
  # Example for VirtualBox:
  #
  config.vm.provider "virtualbox" do |vb|
    # Display the VirtualBox GUI when booting the machine
    vb.gui = false

    # Customize the number of cpus on the VM:
    vb.cpus = "2"
    
    # Customize the amount of memory on the VM:
    vb.memory = "2048"

    vb.customize ["modifyvm", :id, "--ioapic", "on"]
  end
  #
  # View the documentation for the provider you are using for more
  # information on available options.

  # Enable provisioning with a shell script. Additional provisioners such as
  # Ansible, Chef, Docker, Puppet and Salt are also available. Please see the
  # documentation for more information about their specific syntax and use.

  config.vm.provision "shell", path: "./provision.sh", env: {"CLIENT_SECRET" => "$(base64 /Users/hoge/vagrant/key.json)"}
end

Host OS: MacOS Big Sur 11.5.1
Guest OS: Ubuntu 18.04 LTS(ubuntu/bionic64)
Vagrant 2.2.17
Virtualbox 6.1.26

Upvotes: 0

Views: 650

Answers (1)

Frederic Henri
Frederic Henri

Reputation: 53703

The provisioner is not executing on the host but runs on the VM (that's why it runs when you have file on the vagrant directory where Vagrantfile is as this directory is automatically shared with /vagrant on the VM.

If you want to leave the file where it is you should add a file provisioner to copy the key file on the VM and then run the shell provisioner

Upvotes: 1

Related Questions