Chef Json values to ERB files

1.5k Views Asked by At

How are values from data bag JSON files accessed from ERB files in Chef templates.

I have a data bag file named chef-repo/data_bags/test.json containing this data:

{
  "id": "test",
  "test": {
    "name": "doel"
  }
}

Within the chef-repo/cookcooks/test/templates/default.erb I am seeing that <% @test.name %> is accessed and is showing values accurately.

I'd like to understand where the instance variable @test is assigned the value of the data bag within Chef.

1

There are 1 best solutions below

0
On

The data bag gets read in a recipe. The extracted value is then passed to the template where it is then available in the ERB context. This can look something like this:

test = data_bag_item("my_data_bag", "test")

template "/path/to/target/file" do
  source "default.erb"
  variables :test => test
end

You can read more about variables in templates at the template documentation.

As a final remark, you are missing some directories in your cookbook and chef repo. The erb file has to be at chef-repo/cookcooks/test/templates/default/default.erb (notce the added default directory). The data bag item should be in a directory named after the data bag (remember, there are many data bags, each containing many data bag items). Thus, in the code example above, your data bag should be in chef-repo/data_bags/my_data_bag/test.json.