Add new role to Chef.json file with sed

I have a typical .json file for Chef, for example. servername.json

{

  "name": "myserver123",

  "chef_environment": "test",

  "run_list": [

    "role[base-pkg]",

    "role[interesting_stuff]",

    "role[user_apps]"


  ]

}

What I would like to do is use the "one liner" to add a new role after the last role found in the file. Since I never know which roles or how many of them are in the file, I decided to find the final closing bracket "]"and add a new role above this.

I tried the following:

tac servername.json | sed -i '0,/\]/a "role[My_New_Role]"'

thinking that it will find (now) the first β€œ]" and add a new line after it. However, when I run cmd, it adds the string "role [My_New_Role]" 3 times. Twice before "]"and once in the right place after"]"

Questions:

1) 3 , "0" ?

2) AWK, Perl Python (2.7.5)? ?

3) regex lookahead/behind tac?

4) , , , ? ?

0
2

, (vs sed, AWK Perl), , , python json.

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))

:

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

script , .

+3

Perl JSON:

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

, print to_json($j, {pretty => 1})

+5

Source: https://habr.com/ru/post/1534796/


All Articles