rubychef-infrarecipedatabags

Using databag in CHEF recipe


I have been struggling for over a week to solve this issue. Is there anyone who can help me out solving this.

I have a databag mongo, the contents of the databag is:

{ "firstuser": {
"id": "firstuser",
"password": "123",
"db": "mydb",
"role": "readWrite"
},
"seconduser": {
"id": "seconduser",
"password": "123",
"db": "mydb",
"role": "readWrite"
},
"thirduser": {
"id": "thirduser",
"password": "123",
"db": "mydb",
"role": "read"
},
"id": "users"
}

I want to loop through the databag, in order to create users in MongoDB. This is what I have come up with (and a lot more fruitless attempts)

users_databag_item = data_bag_item('mongodb', 'users')
users_databag_item.each_pair do | user, values |
log "db.createUser( { user: '#{values['id']}', pwd: '#{values['password']}', roles: [ { role: '#{values['role']}', db: '#{values['db']}' } ] } )"
end

The output of the script above is;

  1. log[printing the records: db.createUser( { user: 'firstuser', pwd: '123', roles: [ { role: 'read', db: 'mydb' } ] } ) ] action write
  2. log[printing the records: db.createUser( { user: 'seconduser', pwd: '123', roles: [ { role: 'read', db: 'mydb' } ] } ) ] action write
  3. log[printing the records: db.createUser( { user: 'thirduser', pwd: '123', roles: [ { role: 'read', db: 'mydb' } ] } ) ] action write
  4. log[printing the records: db.createUser( { user: '', pwd: '', roles: [ { role: '', db: '' } ] } ) ] action write

Have a look at row 4, it contains an empty record. It seems that the loop also uses ("id": "users"). Is there a way to filter out this entry?

To prove this I have added "id": "users", "password": "123" which resulted in 2 extra empty records.

So, I need to filter out: ("id": "users"). How can I achieve this?


Solution

  • Can put filter for the object type of the values:-

    users_databag_item = data_bag_item('mongodb', 'users')
    users_databag_item.values.each do | values |
        log "db.createUser( { user: '#{values['id']}', pwd: '#{values['password']}', roles: [ { role: '#{values['role']}', db: '#{values['db']}' } ] } )" if !values.is_a? (String)
    end
    

    or

    users_databag_item = data_bag_item('mongodb', 'users')
    users_databag_item.each_pair do | id, values |
        log "db.createUser( { user: '#{values['id']}', pwd: '#{values['password']}', roles: [ { role: '#{values['role']}', db: '#{values['db']}' } ] } )" if !id.eql? "id"
    end