Search code examples
rubyvagrantvagrantfile

Vagrantfile and external config - what am I doing wrong?


Never used Ruby but this seems straight forward enough having looked at a few examples - not working - what am I missing?

vmconfig.yml:

server:   
    hostname: mydomain.com

Vagrantfile:

require 'yaml'
vmconfig = YAML.load_file('vmconfig.yml')

Vagrant.configure(2) do |config|
  config.vm.box = "debian/contrib-jessie64"

  config.vm.provision "shell", inline: <<-SHELL
    apt-get update

    hostname vmconfig["server"]["hostname"]
    config.vm.synced_folder ".", "/vagrant", type: "virtualbox"
end

hostname is not set (to what config file should) when VM is finished building??? If I hardcode the value it works fine???


Solution

  • The best is to use vagrant to define the hostname of the VM like below

      config.vm.provision "shell", inline: <<-SHELL
        apt-get update
      SHELL
    
      config.vm.hostname = vmconfig["server"]["hostname"]
      config.vm.synced_folder ".", "/vagrant", type: "virtualbox"
    

    You can see other available settings that you can define in your Vagrantfile

    If you want to run through the yaml and write from script, you need to do it with string interpolation

      config.vm.provision "shell", inline: <<-SHELL
        apt-get update
        hostname #{vmconfig["server"]["hostname"]}
        .... set other things from yaml with #{<variable>} ....
      SHELL