Chef templates

Chef is a powerful configuration management tool that turns infrastructure into code. With the help of Chef, Users can easily manage, configure and deploy the resources across the network from the central location of the environment (cloud, on-premises, or hybrid).

Templates are used to create a configuration file on the node, by adding the relevant values that are applicable to that particular node during the chef agent run.

Templates are very much similar to files in a chef cookbook. Templates let you create static files with dynamically created content inside.

Consider having a configuration file for a web server like Apache or Nginx. Using templates, you can create a skeleton of the configuration file with all required contents that will remain the same in all nodes. But several places in that configuration skeleton might have details like hostname or IP address of the server, which you can never hard code in there, as these values will be different on different servers. Hence chef-client should place the correct value during runtime at the correct place in the skeleton.

Inside the template file, we can have ruby language statements that will take care of placing correct values dynamically during run time. You can simply create a template file inside the directory cookbooks/{cookbook name}/templates/default/. The template file looks like the one below. Let's create a template file named httpd.conf.erb (inside the directory mentioned.)


DocumentRoot "/var/www/example"


In the above-shown template snippet of httpd.conf.erb, <%= @ip %> will get replaced by the actual IP address of the server. Server details like fqdn, memory, CPU, hostname, IP address, interfaces, and many others can be used just like this example. You can also use ruby code snippets in your templates.

Once you have defined your template file(which ends with a .erb extension inside the previously mentioned cookbook directory), you can use the template using the template resource as shown below.

template '/etc/httpd/httpd.conf' do

source 'httpd.conf.erb'

mode '0644''

owner 'root'

group 'root'

Recent Comments

No comments

Leave a Comment