[英]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.