What is Chef Template, dealing with files in Chef and more

What is Chef Template, dealing with files and more!

In this article we will dig in some of the Chef resources, you can check all about chef here and how to install it by following this link.

What is Chef Template Resource

Simply they are Ruby ERB files which will act as a template for your cookbooks recipes.

How create a template ?

chef generate template <path/of/cookbook> name-of-template

The template will be created inside template folder

ERB Simple Example

My hostname is <%= node['hostname']%>

Now if you want your recipe which creates /etc/motd to get that from template simply run something similar to following in the recipe:

template '/etc/motd' do
source 'file-name.erb'
# output of this ruby will be places in that motd file
action :create
end

 

Dealing with files

There are 4 ways to deal with files in Chef.

1- File
This resource is that you are creating a file and specifying a content as a part of the attributes.

2- Template
With a template you can create a file and create the content dynamically through "source" attribute and a Ruby "erb" template file.

3- Cookbook_file
This is a static file which you will have in the Chef server and ship it to the node. Files will be copied from /files/ folder inside the cookbook.

How create Cookbook_file

chef generate file cookbook/apache/ index.html

This will create the file inside files folder inside default, default means that this is standard file for all operating systems and different nodes.

4- Remote_file

This one will create a file by downloading remotely from different server

remote_file '/var/www/html/pic.png' do
source 'http://whatever.com/name.png'
end

 

Write bash script in Chef

Example:
bash "inline script" do
user "root"
code "mkdir -p /home/meliks/kokowawa && ls -la"
# Below attributes are conditional code that bash will run or not -- those called guard

# You can also add conditions like below:
not_if '[-d /home/meliks/kokowawa]'
only_if '[-d /home/meliks/wowwow]'
end

 

 

 

 


Subscribe to
for video tutorials updates