Chef 简明教程
Chef - Templates
在基础设施中, configuration management 涉及配置主机。总体来说,所有配置都是使用配置文件完成的。Chef 使用模板将配置文件填充动态值。
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 将模板用作食谱中可用的资源。可以从数据包、属性中获取配置文件的动态值,甚至可以通过将它们传递到模板中进行计算。
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.
How to Use It?
Step 1 - 添加模板到食谱。
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 - 添加 ERB 模板文件。
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 - 上传修改后的食谱到 Chef 服务器。
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 - 验证上传文件的内容。
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!
Workflow
Chef 将 Erubis 用作其模板语言。它允许在模板的特殊符号中嵌入纯粹的 Ruby 代码。
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.