Gabriel
Gabriel

Reputation: 109

From ruby array to json in bash

In my chef environment I have a variable like this:

"repl_set_members": ["tmongo01", "tmongo02", "tmongo03"]

I need to create JSON to be sent to a Mongo instance and build the replica set.

I created a bash file from a template with:

template "/opt/create_repl_set.sh" do
  source "create_repl_set.sh.erb"
  owner 'root'
  group 'root'
  mode "0755"
  variables(
      :repl_set_name => node['mongodb']['shardname'],
      :members => node['mongodb']['repl_set_members']
  )
end

And in the bash template I would have something like this:

config = "{_id: '<%= @repl_set_name %>', members: [
<% @members.each_with_index do |name,number| %>
{_id: <%= "#{number}" %>, host: '<%= "#{name}" %>:27017'},
<% end %>
] }"

mongo localhost:27091 --eval "JSON.stringify(db.adminCommand({'replSetInitiate' : $config}))"

But the resulting JSON includes a last comma which I don't know how to get rid of.

Does anyone have a better idea?

Upvotes: 0

Views: 203

Answers (2)

coderanger
coderanger

Reputation: 54247

What you probably want is an execute resource an .to_json

mongo_cmd = {
  'replSetInitiate' => {
    '_id' => node['mongodb']['shardname'],
    'members' => node['mongodb']['repl_set_members'].each_with_index.map { |name, number|
      {'_id' => number, 'host' => "#{name}:27017"}
    },
  },
}

execute "mongo localhost:27091 --eval 'JSON.stringify(db.adminCommand(#{mongo_cmd.to_json}))'"

Upvotes: 1

Aserre
Aserre

Reputation: 5072

A quick and dirty way to remove your last comma would be to use bash string manipulation and call your script as follow :

mongo localhost:27091 --eval "JSON.stringify(db.adminCommand({'replSetInitiate' : ${config/%,/}))"

Note that this will always delte the last comma in your JSON value, so it will only work if your resulting JSON always has an extra comma (i.e. even when your JSON is empty)

Upvotes: 1

Related Questions