In Infrastructure, configuration management is all about how well one configures the hosts. In general, all the configurations are done using the configuration files. Chef uses templates to be able to fill the configuration file with dynamic values.
Chef provides templates as a resource which can be used in the recipe. Configuration files’ dynamic values can be retrieved from data bags, attributes or even calculate them by passing them into the template.
Step 1 − Add the template to the recipe.
vipin@laptop:~/chef-repo $ subl cookbooks/<Cookbook Name>/recipes/default.rb template '/tmp/message' do source 'Test.erb' variables( hi: 'Tesing', world: 'Welt', from: node['fqdn'] ) end
Step 2 − Add ERB Template file.
vipin@laptop:~/chef-repo $ subl cookbooks/<Cookbook Name>/templates/default/test.erb <%- 4.times do %> <%= @hi %>, <%= @world %> from <%= @from %>! <%- end %>
Step 3 − Upload the modified cookbook to Chef server.
vipin@laptop:~/chef-repo $ knife cookbook upload <Cookbook Name> Uploading my_cookbook [0.1.0] Run Chef Client on your node: user@server:~$ sudo chef-client ...TRUNCATED OUTPUT... [2017-01-14T20:41:21+00:00] INFO: Processing template[/tmp/ message] action create (my_cookbook::default line 9) [2017-01-14T20:41:22+00:00] INFO: template[/tmp/message] updated content
Step 4 − Validate the content of the uploaded file.
user@server:~$ sudo cat /tmp/message Hallo, Welt from vagrant.vm! Hallo, Welt from vagrant.vm! Hallo, Welt from vagrant.vm! Hallo, Welt from vagrant.vm!
Chef uses Erubis as its template language. It allows embedding pure Ruby code inside special symbols in the templates.
<%= %> is used if you want to print the value of a variable or Ruby expression into the generated file.
<%- %> is used if you want to embed Ruby logic into your template file. We use it to loop our expression four times.