厨师Ruby循环遍历.erb模板文件中的属性 [英] Chef Ruby loop over attributes in an .erb template file
问题描述
所以这可能有点混乱,但与我同在。简而言之,我想使用某个键值循环所有属性,然后将它们插入到模板中,如果值不为空。这是我的代码:
So this might be a little confusing but bear with me. In short I want to loop over all attributes with a certain key value and then insert them into a template if the values are not empty. Here is my code:
属性:
# === Default file Configurations
#
default['elasticsearch']['default']['ES_USER'] = ''
default['elasticsearch']['default']['ES_GROUP'] = ''
default['elasticsearch']['default']['ES_HEAP_SIZE'] = ''
default['elasticsearch']['default']['MAX_OPEN_FILES'] = ''
default['elasticsearch']['default']['MAX_LOCKED_MEMORY'] = 'unlimited'
default['elasticsearch']['default']['MAX_MAP_COUNT'] = ''
default['elasticsearch']['default']['LOG_DIR'] = '/var/log/elasticsearch'
default['elasticsearch']['default']['DATA_DIR'] = '/var/lib/elasticsearch'
default['elasticsearch']['default']['WORK_DIR'] = '/tmp/elasticsearch'
default['elasticsearch']['default']['CONF_DIR'] = '/etc/elasticsearch'
default['elasticsearch']['default']['CONF_FILE'] = '/etc/elasticsearch/elasticsearch.yml'
default['elasticsearch']['default']['RESTART_ON_UPGRADE'] = ''
模板:
<% node['elasticsearch']['default'].each do |host| -%>
<% if node.elasticsearch.default.host not nil -%>
<%= host %>=<%= node.elasticsearch.default.host %>
<% end %>
OUTPUT(希望):
OUTPUT (hopefully):
MAX_LOCKED_MEMORY=unlimited
LOG_DIR=/var/log/elasticsearch
DATA_DIR=/var/lib/elasticsearch
WORK_DIR=/tmp/elasticsearch
CONF_DIR=/etc/elasticsearch
CONF_FILE=/etc/elasticsearch/elasticsearch.yml
我的红宝石不是最好的,因为我只是从所有这些东西开始,但是我找不到这种情况的例子。任何帮助都会很棒,谢谢。
My ruby isn't the best because I'm just starting out with all of this stuff but I couldn't find any examples for this type of situation. Any help would be great, thanks.
推荐答案
你可能的意思是:
<% node['elasticsearch']['default'].each do |key, value| -%>
<% unless value.empty? -%>
<%= key %>=<%= value %>
<% end %>
<% end %>
当迭代 Hash
时,超过其键值对。所以对于第一次迭代, key
将是'ES_USER'
和值
将是''
(不是 nil
...)。
When iterating over a Hash
, you go over its key-value pairs. So for the first iteration, key
will be 'ES_USER'
, and value
will be ''
(which is not nil
...).
接下来,您检查该值不是 blank?
,并打印出 key = value
行。
Next you check that the value is not blank?
, and print out the key=value
line.
这篇关于厨师Ruby循环遍历.erb模板文件中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!