[英]Generate Templates from Json variables
I want to generate some zabbix templates for some local microservices (variables stored in a json file), please see the code below: 我想为某些本地微服务(存储在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
And this is my services.json file: 这是我的services.json文件:
{
"microservice1":{
....... ,
"httpport": "27200"
},
"microservice2":{
......,
"httpport": "25201"
}
}
Basically in this method when I'm doing the loop for each microservice it run successfully until it ends the loop. 基本上,在这种方法中,当我为每个微服务执行循环时,它将成功运行,直到结束循环。 When it creates the haproxy.xml it shows " undefined local variable or method `httpport' for main:Object (NameError)" I tried to put httpport variable outside the loop and it's shows the same error. 当它创建haproxy.xml时,它显示“ main:Object(NameError)的未定义局部变量或方法'httpport'”我试图将httpport变量放入循环之外,并且显示了相同的错误。
Please also see a part of the erb file(if I replace the <%= httpport %> with 25201, the file is generated corectly): 另请参阅erb文件的一部分(如果将<%= httpport%>替换为25201,则该文件将完全生成):
<items><% service.each do |microservice| %>
<item>
<name>haproxy <%= microservice %> - <%= httpport %></name>
......
</item><% end %>
Here is a working example, if you paste this into a ".rb" file, then you can run it. 这是一个工作示例,如果将其粘贴到“ .rb”文件中,则可以运行它。
Problem with your version: binding
does not contain httport
(and even if it would contain it, it would be the same for all microservices because it does not get re-assigned.): solution: access the the JSON (ruby hash) data in the template and then loop from there. 您的版本存在问题: 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.