0

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???

Frederic Henri
  • 51,761
  • 10
  • 113
  • 139
Alex.Barylski
  • 2,843
  • 4
  • 45
  • 68

1 Answers1

1

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
Frederic Henri
  • 51,761
  • 10
  • 113
  • 139
  • Thank you for the updated response but I am very curious as to why none of the examples I looked at seemed to use interpolated strings (https://stackoverflow.com/a/26394449/897075) this is exactly what I am trying to do. I have to admit, the string interpolation looks awful but it did seem to do the trick - but now I am trying to understand why? What is different between all these examples and what I have? – Alex.Barylski Jul 17 '17 at 15:57
  • I think I may have just figured out why...the examples I looked at are using config.vm.XXX - my bad :) – Alex.Barylski Jul 17 '17 at 16:00
  • 1
    no it is not the same - see my first code snippet does not use string interpolation, vagrant will get the expected hostname directly by reading the yaml file; in the 2nd part though I need string interpolation as the whole script is run within a text (the SHELL string variable in this case) so you need a way to tell vagrant the hostname part is has to be read from yaml and its a variable not just some random text – Frederic Henri Jul 17 '17 at 16:01
  • Right right - gotcha...thank you very much!!! Have yourself a great day :) – Alex.Barylski Jul 17 '17 at 16:08