0

Vagrantfile:

require 'json'

file = File.read('blueprint.json')
azure_data = JSON.parse(file)

Vagrant.configure('2') do |config|
  config.vm.define "master" do |node|
    node.vm.provider :azure do |azure, override|
      azure_data.each do |hash|
        hash.each do |key, value|
          azure[key] = value
        end
      end
      azure.vm_name = "somename"
    end
  end
end

vagrant up gives this error:

Microsoft Azure Provider:
* The following settings shouldn't exist: []

Also, if I add puts('something') into the hash.each loop, it gets output not once per each property of JSON file, but 6 times (¿?) per each property

blueprint.json:

{
    "admin_username":"someuser",
    "location":"northeurope",
    "resource_group_name":"resourcegroup",
    "tcp_endpoints":"5000",
    "virtual_network_name":"vnetname",
    "vm_size":"Standard_DS1"
}
4c74356b41
  • 69,186
  • 6
  • 100
  • 141

2 Answers2

0

Your JSon file is already a JSon object so when you'll read it, you directly have the key, value pair. You can do the following just to check

require 'json'

file = File.read('blueprint.json')
azure_data = JSON.parse(file)

azure_data.each do |key, value|
  p key
  p value
end

so when reading your JSon you can skip the hash part, ruby already knows this is a hash. Then you want to set the object properties dynamically, you need to use send method

require 'json'

file = File.read('blueprint.json')
azure_data = JSON.parse(file)

Vagrant.configure('2') do |config|
  config.vm.define "master" do |node|
    node.vm.provider :azure do |azure, override|
      azure_data.each do |key, value|
        azure.send("#{key}=", value)
      end
      azure.vm_name = "somename"
    end
  end
end
Frederic Henri
  • 51,761
  • 10
  • 113
  • 139
0

It appears that it is possible after all, courtesy of this.

config.vm.define "master" do |node_dotnet|
  node_dotnet.vm.provider :azure do |azure, override|
    azure_data.each do |key, value|
      azure.instance_variable_set("@#{key}", value)
    end 
    azure.vm_name = "master"
  end
end

Man, Ruby has a horrible syntax

ps. For some reason, not all of those methods work.

Community
  • 1
  • 1
4c74356b41
  • 69,186
  • 6
  • 100
  • 141
  • good I was looking at this one http://stackoverflow.com/questions/7849521/set-attribute-dynamically-of-ruby-object and did test .. didnt see you have answered meanwhile, good you found – Frederic Henri Mar 26 '17 at 16:06
  • why does it need this weird syntax? I can't understand it at all. `send("#{key}=", value)` @FrédéricHenri – 4c74356b41 Mar 26 '17 at 16:09
  • `#{key}` is ruby string interpolation and send method takes argument follow by = and the value as 2nd parameter – Frederic Henri Mar 26 '17 at 16:10
  • @FrédéricHenri but why does in this case it needs another syntax? `instance_variable_set("@#{key}", value)` so string interpolation is both `@#{}` and `#{}`? – 4c74356b41 Mar 26 '17 at 16:11