Example of data_bag usage in Chef

Let's take a look at a short example of how to use data_bag in ChefDK. Required prerequisite for this example is set up Chef workstation and web console running on Chef server.

Step1: web open console and create a new data bag. Let's name it chef_secrets.



Step 2: add some json-formatted data item. For example, name it 'xcode_credentials'



Step 3: use data bag in your receipe

To access data bag you can use following approach:

 credentials = data_bag_item('chef_secrets', 'xcode_credentials')

 environment = {
  'MY_USERNAME' => credentials['login'],
  'MY_PASSWORD' => credentials['password']
 }

You can also look up on data bag using knife. For example to list all data bags use

 knife data bag list


To see content of the data bag from our example above:

knife data bag show chef_secrets xcode_credentials



Comments