分类: 系统运维
2015-04-01 18:09:20
具体不解释了,在Docker上做测试,注释了一些没办法实现的功能如require/notify等。
[root@localhost puppet]# tree modules/
modules/
└── apache
├── manifests
│ └── init.pp
└── templates
└── vhost.conf.erb
3 directories, 2 files
现在看erb的模板,记住下边个常见的用法:
1)
<% if has_variable?("YOUR_VARS") then -%>
<% @YOUR_VARS.each do |f| -%>
cfg_file=/etc/<%= f %>
<% end -%>
2)
<%if @YOUR_VARS.is_a? Array -%>
<% @YOUR_VARS.each do |name| -%>
<%= name %><% end-%>
<% end -%>
[root@localhost puppet]# more modules/apache/templates/vhost.conf.erb
NameVirtualHost *:<%= @port %>
ServerName <%= @name %>
<%if @serveraliases.is_a? Array -%>
<% @serveraliases.each do |name| -%><%= " ServerAlias #{@name}\n" %><% end
-%>
<% elsif @serveraliases != '' -%> # <%- else %>
<%= " ServerAlias #{@serveraliases}" -%>
<% end -%>
DocumentRoot <%= @docroot %>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
ErrorLog /var/log/apache2/<%= @name %>_error.log
LogLevel warn
CustomLog /var/log/apache2/<%= @name %>_access.log combined
ServerSignature On
# 关于ERB的细节。
<% instance =1 %> # ruby代码
<% File.open("/etc/passwd","r").each_line do |line| -%> # File函数 <% XX %>XX是嵌入的Ruby代码和表达式
<% vars=line.split(":")%> # 字符串函数
<%= "#{vars[0]}" %>: # 打印array的值。
<%= @VAR %> # 打印计算的值,可以是Facts或者传递进去的变量。
《%% XX %> # 输出<% XX %>
<% instance+=1 %>
<% end -%>
注意<%= VAR %> 和 《%= @VAR %> 区别,第一个是RUBY表达式的值,第二个是facts或者传递进去的变量。
[root@localhost puppet]# more modules/apache/manifests/init.pp
define apache::vhost(
$docroot,
$port,
$priority,
$ssl=true,
$serveraliases = '',
$template='apache/vhost.conf.erb',
){
# include apache
file {"/etc/apache2/sites-enabled/${priority}-${name}": #这里的resource的title不能为constant,否则会重复声明file 资源多次(duplicated)。
content => template($template),
owner => 'root',
group => 'root',
mode => '0640',
# require => Class['apache::install'],
# notify => Class['apache::service'],
}
}
[root@localhost puppet]# cat production/production.pp
node default {
apache::vhost { '':
port => '80' ,
docroot => '/var/www/',
ssl =>false ,
priority =>'10',
serveraliases =>'web.example.com',
}
apache::vhost { '':
port => '81' ,
docroot => '/var/www/',
ssl =>false ,
priority =>'20',
serveraliases =>'db.example.com',
}
}
# Optional
mkdir -pv/etc/apache2/sites-enabled
[root@localhost sites-enabled]# more 20-
NameVirtualHost *:81
ServerName
ServerAlias db.example.com DocumentRoot /var/www/
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
ErrorLog /var/log/apache2/_error.log
LogLevel warn
CustomLog /var/log/apache2/_access.log combined
ServerSignature On