簡體   English   中英

從Json變量生成模板

[英]Generate Templates from Json variables

我想為某些本地微服務(存儲在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文件的一部分(如果將<%= httpport%>替換為25201,則該文件將完全生成):

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

這是一個工作示例,如果將其粘貼到“ .rb”文件中,則可以運行它。

您的版本存在問題: binding不包含httport (即使包含它,它也將對所有微服務都是相同的,因為它不會得到重新分配。):解決方案:訪問以下位置的JSON(紅寶石哈希)數據模板,然后從那里循環。

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM