【问题标题】:Overriding default hashes without merging覆盖默认哈希而不合并
【发布时间】:2016-09-12 06:31:09
【问题描述】:

我正在尝试使用 lusis/chef-logstash 的 chef-logstash 食谱,并且很难覆盖 ['logstash']['instance']['server']['config_templates'] 属性。当我通过我的包装食谱wrapper-logstash 进行设置时,我得到了默认值的合并哈希以及我通过包装食谱添加的内容。

作为参考,我在食谱中使用的代码是:

#force override our attributes (or attempt to anyways)
#attributes = node['logstash']['instance'][name]
node.force_override['logstash']['instance']['server']['config_templates'] = {}
node.force_override['logstash']['instance']['server']['config_templates'] = {
   'input_redis' => 'config/input_redis.conf.erb',
   'filter_sidewinder' => 'config/filter_sidewinder.conf.erb',
   'output_elasticsearch' => 'config/output_elasticsearch.conf.erb'
}

我怎样才能干净地覆盖此属性,使其仅设置为我的包装食谱中的内容?

【问题讨论】:

  • 谢谢,赛斯。那是我在尝试研究此问题时遇到的博客之一。 :) 该帖子讨论了哈希如何在添加和删除方面优于数组,但我在帖子中没有看到有关如何进行删除的示例,也没有看到任何表明上面的代码不正确的内容。我怀疑我对某些事情很执着,但对于我的生活,我无法弄清楚是什么。 :(
  • 你不能......这就是诺亚所说的。您需要将它们设置为nil
  • 我还建议您询问 John Vincent。这是他的食谱,这个问题似乎比 Stackoverflow 更适合作者回答的 GitHub 问题。
  • 我会按照你的建议跟进约翰。澄清一下,哈希只能在 Chef 中合并。即使使用 force_override,也永远无法删除键?这似乎很尴尬。

标签: chef-infra logstash chef-solo


【解决方案1】:

在@LearnChef 工作人员的大量帮助下,解决方案是在我的包装配方中使用 ruby​​ 代码来迭代密钥并删除它们。一个问题是确保迭代和删除循环使用与原始默认属性相同的属性优先级,这些属性在源 LWRP 中设置的不是默认级别,而是正常级别。

最终代码如下:

#clear out the default config templates
attributes = node['logstash']['instance'][name]
node.normal['logstash']['instance'][name]['config_templates'].keys.each do |k|
  node.normal['logstash']['instance'][name]['config_templates'].delete(k)
end
node.force_override['logstash']['instance']['server']['config_templates'] = {
  'input_redis' => 'config/input_redis.conf.erb',
  'filter_sidewinder' => 'config/filter_sidewinder.conf.erb',
  'output_elasticsearch' => 'config/output_elasticsearch.conf.erb'
}

【讨论】:

  • 此时,您也可以只提供自己的模板并忽略其中的那些变量。
【解决方案2】:

在类似的用例中,我只是想将我的散列设置为空散列。一个对我有用的快速而肮脏的解决方法是将属性设置为 空数组,如下所示:

原始属性定义:

#give us an elasticsearch cluster with these plugins by default
default['elasticsearch']['plugins'] = {
  'karmi/elasticsearch-paramedic' => {},
  'mobz/elasticsearch-head' => {},
  'jlinn/elasticsearch-cloud-rackspace' => {
    'url' => 'https://github.com/jlinn/elasticsearch-cloud-rackspace/releases/download/v0.4.1/elasticsearch-cloud-rackspace-0.4.1.zip'
  }
}

我在环境中的定义:

"elasticsearch": {
  "plugins": []
}

这是使用它的代码:

node[:elasticsearch][:plugins].each do | name, config |
  next if name == 'elasticsearch/elasticsearch-cloud-aws' && !node.recipe?('aws')
  next if name == 'elasticsearch/elasticsearch-cloud-gce' && !node.recipe?('gce')
  install_plugin name, config
end

把它放在那里,以防你也在寻找快速/临时的破解方法。希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 2017-04-27
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多