Add a new role to a Chef .json file with Sed

懵懂的女人 提交于 2019-12-07 06:31:25

I don't know if this is the best approach (vs sed, AWK, or Perl) but it is straightforward to do what you're asking using python's json library.

import json

# read the file as a dict using json.loads
d = json.loads(open('servername.json', 'r').read())

# add your new role to the end of the run_list
d['run_list'].append('role[My_New_Role]')

# write new json to file (specify a new file, or overwrite if you prefer)
open('new_servername.json', 'w').write(json.dumps(d, indent=2))

The output file looks like:

{
  "chef_environment": "test", 
  "name": "myserver123", 
  "run_list": [ 
    "role[base-pkg]", 
    "role[interesting_stuff]", 
    "role[user_apps]",
    "role[My_New_Role]"
  ]
}

It's pretty easy to modify this code into a script with the filename as an input so that it's easy to run multiple times.

Perl with the JSON module:

cat servername.json | perl -MJSON -0 -ne '$j = decode_json($_); push @{$j->{run_list}}, q<role[My_New_Role]>; print encode_json($j)'

you can pretty-print it by replacing the print command with print to_json($j, {pretty => 1})

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!