0

I'm new to Chef and I'm having some problems to get the values from data_bags with nested attributes.

{   
  "id": "bareos-fd",   
  "description": "Client resource of the Director itself.",   
  "address": "localhost",   
  "job": {
    "backup-bareos-fd": {
      "jobdefs": "DefaultJob"
    },
    "BackupCatalog": {
      "description": "Backup the catalog database (after the nightly save)",
        "jobdefs": "DefaultJob",
        "level": "Full",
        "fileset": "Catalog",
        "schedule": "WeeklyCycleAfterBackup",
        "run_before": "/usr/lib/bareos/scripts/make_catalog_backup.pl MyCatalog",
        "run_after": "/usr/lib/bareos/scripts/delete_catalog_backup",
        "bootstrap": "|/usr/bin/bsmtp -h localhost -f \\\"\\(Bareos\\) \\\" -s \\\"Bootstrap for Job %j\\\" root@localhost",
        "priority": "11"
     },
     "RestoreFiles": {
       "type": "Restore",
       "fileset": "LinuxAll",
       "storage": "File",
       "pool": "Incremental",
       "messages": "Standard",
       "where": "/tmp/bareos-restores"
     }   
   } 
 }

How can I write a foreach to get the nested values (like BackupCatalog and its values?)

1 Answers1

1

The object returned from data_bag_item works like a hash:

bag = data_bag_item('something', 'bareos-fd')
bag['job']['BackupCatalog'].each do |key, value|
  # ...
end
coderanger
  • 52,400
  • 4
  • 52
  • 75
  • The job key is dynamic. What I'm trying to do is create a file with the key as the name and with the values inside. This databag is a example with the default configuration file, the BackupCatalog is only for this specific client. My problem is to reference the dynamic kv. This could be like ` "job": { "another_job": { "type": "other" } } ` I have a data_bag named bareos_clients with all clients inside. I'm able to read all the contents, but I have no clue on how to loop through the job entries. – Thiago Ramos Fanfoni May 01 '17 at 19:41
  • It's all just Ruby code is my point. Look up the Ruby `Hash` and `Array` classes and you'll find whatever methods you need. – coderanger May 01 '17 at 21:08