【问题标题】:Generate Templates from Json variables从 Json 变量生成模板
【发布时间】:2016-05-22 07:06:20
【问题描述】:

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

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文件的一部分(如果我将替换为25201,则文件正确生成):

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

【问题讨论】:

    标签: ruby json loops hash erb


    【解决方案1】:

    这是一个工作示例,如果将其粘贴到“.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>
    

    【讨论】:

    • 谢谢,正在工作,但在 .erb 文件中有 ...
    猜你喜欢
    • 2021-07-25
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多