.each 循环中的 Chef ERB 模板变量

Chef ERB template variable in a .each loop

在食谱中,我有一个模板资源:

clustered_machines = Array.new
nodes.each do |node|
  clustered_machines << node['hostname']
end

zookeeper_data_dir=node["lc_kafka"]["zookeeper_datadir"]
zookeeper_client_port=node["lc_kafka"]["zookeeper_client_port"]
zookeeper_client_Port_Address=node['hostname']
delete_topic=node["lc_kafka"]["delete_topic"]
brokerID=node["brokerID"]
logdir="#{kafka_home}/logs"
template "server.properties" do
  path "/#{kafka_home}/config/server.properties"
  source "server.properties.erb"
  owner "kafka"
  group "kafka"
  mode "0644"
  variables(
      :brokerID => brokerID,
      :logdir => logdir,
      :zookeeper_machines => clustered_machines,
      :zookeeper_client_port => zookeeper_client_port,
      :delete_topic_bool => delete_topic
  )
end

在 erb 文件中我有以下内容:

log.retention.ms=-1
log.segment.bytes=1073741824
log.retention.check.interval.ms=300000
<%
zookeeper_connection_string = ""
@zookeeper_machines.each do |name|
  zookeeper_connection_string = zookeeper_connection_string + "#{name}"
end
zookeeper_connection_string = zookeeper_connection_string.chomp(", ")
%>
zookeeper.connect=<%= @zookeeper_connection_string %>
zookeeper.connection.timeout.ms=6000
group.initial.rebalance.delay.ms=0

磁盘上的最终结果文件应该有这个 zookeeper_connection_string:

zookeeper.connect=kafka01:2181,kafka02:2181,kafka03:2181

这应该来自循环:

<%
zookeeper_connection_string = ""
@zookeeper_machines.each do |name|
  zookeeper_connection_string = zookeeper_connection_string + "#{name}":<%= @zookeeper_client_port %>
end
zookeeper_connection_string = zookeeper_connection_string.chomp(", ")
%>
zookeeper.connect=<%= @zookeeper_connection_string %>

但是这个来自模板资源定义的变量抛出了一个异常,因为那个循环中的那个变量不存在:

<%= @zookeeper_client_port %>

该变量只能在循环外定义。

我的问题是...有没有办法在循环中使用该变量? 谢谢你。 加布里埃尔

稍后编辑:

我修改了这部分:

 nodes.each do |node|
   clustered_machines << "#{node['hostname']}:#{zookeeper_client_port}"
 end

现在我已准备好要插入的字符串:

  [2019-11-01T20:46:00+02:00] WARN: clustered_machines are: ["kafka03:2181", "kafka02:2181", "kafka01:2181"]

我仍然不知道如何创建

zookeeper.connect=<%= @zookeeper_connection_string %>

解决方法:

<%
zookeeper_connection_string = ""
@zookeeper_machines.each do |name|
  zookeeper_connection_string = zookeeper_connection_string + "#{name},"
end
zookeeper_connection_string = zookeeper_connection_string.chomp(",")
%>
zookeeper.connect=<%= zookeeper_connection_string %>

最终结果是:

zookeeper.connect=kafka01:2181,kafka02:2181,kafka03:2181