Chef模板生成指定结构plugin.json文件的实现疑问
如何用Chef模板生成符合New Relic插件要求的plugin.json文件?
我来帮你搞定这个Chef模板生成JSON的问题!你的当前模板只输出了单个name字段的JSON,没法满足New Relic插件需要的完整结构,下面是具体的修改步骤:
1. 更新Recipe中的Template块
首先我们要在recipe里传递所有需要的agent配置参数,用Node属性来管理这些值会更灵活(方便后续在角色/环境里调整)。修改后的template代码块如下:
template "#{plugin_json_path}" do source 'plugin.json.erb' owner "root" group "root" mode "0644" variables( agent: { name: node['newrelic_npi']['name'], host: node['newrelic_npi']['host'] || 'localhost', # 配置缺失时用默认值 metrics: node['newrelic_npi']['metrics'] || 'status,newrelic', user: node['newrelic_npi']['user'] || 'root', passwd: node['newrelic_npi']['passwd'] || 'mysecret' } ) action :create end
这里把agent的所有配置打包成一个哈希,通过variables传递给模板,同时给每个字段设置了默认值,避免配置缺失时出错。
2. 修改plugin.json.erb模板
接下来调整模板内容,构建符合要求的完整JSON结构:
<%= Chef::JSONCompat.to_json_pretty({ agents: [ @agent ] }) %>
模板里我们创建了顶层哈希,其中agents是一个数组,把从recipe传递过来的@agent哈希放入数组中,最后用Chef::JSONCompat.to_json_pretty生成格式化的漂亮JSON。
最终效果
执行这个recipe后,生成的plugin.json会完全匹配你想要的结构:
{ "agents": [ { "name": "sqlhost", "host": "localhost", "metrics": "status,newrelic", "user": "root", "passwd": "mysecret" } ] }
如果以后需要添加多个agent,只需要把variables里的agent改成agents数组(比如agents: node['newrelic_npi']['agents']),然后模板里对应改成agents: @agents即可。
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

