首页 > 代码库 > 在Puppet中用ERB模板来自动配置Nginx虚拟主机
在Puppet中用ERB模板来自动配置Nginx虚拟主机
模板文件是在puppet模块下面templates目录中以”.erb”结尾的文件,puppet模板主要用于文件,例如各种服务的配置文件,相同的服务,不同的配置就可以考虑使用模板文件,例如Nginx和Apache的虚拟主机配置就可以考虑采用ERB模板,nginx的安装在这里建议用系统内部自带的YUM源来安装或其它第三方YUM源来安装,如果是用Nginx的官方源来安装nginx的话,我们可以查看下/etc/yum.repos.d/nginx.repo文件内容,如下所示:
[nginx] name=nginx repo baseurl=http://nginx.org/packages/centos/$releasever/$basearch/ gpgcheck=0 enabled=1
第二种方式就是通过createrepo自建自己的YUM源,这种方式更加宁活,我们可以在nginx官网去下载适合自己的rpm包,然后添加进自己的YUM源,在自动化运维要求严格的定制环境中,绝大多数运维同学都会选择这种方法。大家通过此种方式安装nginx以后会发现,确实比源码安装Nginx方便多了,像自动分配了运行nginx的用户nginx:nginx,Nginx的日志存放会自动保存在/var/log/nginx下,其工作目录为/etc/nginx。
像Puppet其它初级知识点我这里就略过了,我直接贴上文件内容,/etc/puppet的文件结构如下:
|-- auth.conf |-- fileserver.conf |-- manifests | |-- nodes | | |-- client.cn7788.com.pp | | `-- test.cn7788.com.pp | `-- site.pp |-- modules | `-- nginx | |-- files | |-- manifests | | `-- init.pp | `-- templates | |-- nginx.conf.erb | `-- nginx_vhost.conf.erb `-- puppet.conf
site.pp的文件内容如下:
import "nodes/*.pp"
client.cn7788.com.pp的文件内容如下所示:
node ‘client.cn7788.com‘ { include nginx nginx::vhost {‘client.cn7788.com‘: sitedomain => "client.cn7788.com" , rootdir => "client", } }
test.cn7788.com.pp的文件内容如下所示:
node ‘test.cn7788.com‘ { include nginx nginx::vhost {‘test.cn7788.com‘: sitedomain => "test.cn7788.com" , rootdir => "test", } }
/etc/puppet/modules/nginx/manifests/init.pp文件内容如下所示:
class nginx{ package{"nginx": ensure =>present, } service{"nginx": ensure =>running, require =>Package["nginx"], } file{"nginx.conf": ensure => present, mode => 644,owner => root,group => root, path => "/etc/nginx/nginx.conf", content=> template("nginx/nginx.conf.erb"), require=> Package["nginx"], } } define nginx::vhost($sitedomain,$rootdir) { file{ "/etc/nginx/conf.d/${sitedomain}.conf": content => template("nginx/nginx_vhost.conf.erb"), require => Package["nginx"], } }
/etc/puppet/modules/nginx/templates/nginx.conf.erb文件内容如下所示:
user nginx; worker_processes 8; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { use epoll; worker_connections 51200; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main ‘$remote_addr - $remote_user [$time_local] "$request" ‘ ‘$status $body_bytes_sent "$http_referer" ‘ ‘"$http_user_agent" "$http_x_forwarded_for"‘; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; }
/etc/puppet/modules/nginx/templates/nginx_vhost.conf.erb文件内容如下所示:
server { listen 80; server_name <%= sitedomain %>; access_log /var/log/nginx/<%= sitedomain %>.access.log; location / { root /var/www/<%= rootdir %>; index index.php index.html index.htm; } }
本文出自 “抚琴煮酒” 博客,请务必保留此出处http://yuhongchun.blog.51cto.com/1604432/1569791
在Puppet中用ERB模板来自动配置Nginx虚拟主机