从 Json 个变量生成模板

Generate Templates from Json variables

我想为一些本地微服务生成一些zabbix模板(变量存储在json文件中),请看下面的代码:

def self.haproxyTemplates
  file = File.read('./services.json')
  data_hash = JSON.parse(file)

  service = data_hash.keys
  service.each do |microservice|
  puts "Microservice: #{microservice}"
  httpport = data_hash["#{microservice}"]['httpport']
  puts "httpPort: #{httpport}"
  end

  open("./haproxy.xml", 'w+') { |f| f.chmod(0755)
  template=IO.read('./haproxyhealth.xml.erb')
  x = ERB.new(template).result(binding)
  f << "#{x}\n"
  }
end

这是我的 services.json 文件:

{
 "microservice1":{
  ....... ,
  "httpport": "27200"
   },
   "microservice2":{
   ......,
   "httpport": "25201"
   }
}

基本上在这个方法中,当我为每个微服务执行循环时,它 运行 成功,直到它结束循环。当它创建 haproxy.xml 它显示 “main:Object (NameError) 的未定义局部变量或方法‘httpport’” 我试图将 httpport 变量放在循环之外,但它显示了同样的错误。

请同时查看erb文件的一部分(如果我将<%= httpport %>替换为25201,文件会正确生成):

 <items><% service.each do |microservice| %>
            <item>
                <name>haproxy <%= microservice %> - <%= httpport %></name>
 ......
 </item><% end %>   

这是一个工作示例,如果您将其粘贴到“.rb”文件中,那么您可以运行它。

你的版本有问题:binding 不包含 httport(即使它包含它,它对所有微服务都是一样的,因为它不会被重新分配。) : 解决方案:访问模板中的 JSON(ruby 散列)数据,然后从那里循环。

require 'erb'

# data = parse JSON from file, inline here as example

data = {
  'microservice1' => {
    'httpport' => '27200'
  },
  'microservice2' => {
    'httpport' => '27201'
  }
}

open("haproxy.xml", 'w+') do |file|
  template = ERB.new(DATA.read)
  file << template.result(binding)
  file << "\n"
end


__END__
<items>
  <% data.each do |name, info| %>
    <item>
      <name>haproxy <%= name %> - <%= info['httpport'] %></name>
    </item>
  <% end %>
</items>