使用puppet配置本网站


以下只是一个示例,描述LNMP使用puppet配置的大致方案,里面的用户名和密码不是真实数据。

LNMP主要包含nginx,mysql,php和网站(site,这里是blog)模块。文件结构如下:

├── manifests
│   └── site.pp
└── modules
    ├── blog
    │   ├── files
    │   │   └── wp-config.php
    │   ├── manifests
    │   │   └── init.pp
    │   └── templates
    │       └── nginx.conf.erb
    ├── mysql
    │   ├── files
    │   └── manifests
    │       └── init.pp
    ├── nginx
    │   ├── files
    │   └── manifests
    │       └── init.pp
    └── php
        ├── files
        └── manifests
            └── init.pp

顶层的site.pp如下:

node 'wheezy32' {
  include nginx
  include php

  # TODO change root password
  $mysql_root_password = 'foo'

  include mysql
  include blog
}

nginx其实很简单,就是package+service。

class nginx {

  package { 'nginx': ensure => installed }

  service { 'nginx':
    ensure  => running,
    require => Package['nginx'],
  }

}

php也不难,这里仅安装了php5-fpm和php5-mysql。

class php {

  package { 'php5-fpm': ensure => present }

  service { 'php5-fpm':
    ensure  => running,
    require => Package['php5-fpm'],
  }

  package { 'php5-mysql': ensure => present }

}

mysql稍微复杂点,需要通过exec设置root password(参考这里),另外注意service的名字可能不是mysqld,而是mysql。mysql root password在site.pp中设定。

class mysql {
  package { 'mysql-server': ensure => installed }

  service { 'mysql':
    ensure  => running,
    require => Package['mysql-server'],
  }

  exec { 'set-root-password':
    path    => ['/bin', '/usr/bin'],
    unless  => "mysqladmin -uroot -p$mysql_root_password status",
    command => "mysqladmin -uroot password $mysql_root_password",
    require => Service['mysql'],
  }

  package { 'mysql-client': ensure => installed }
}

最后是最重要也是最复杂的网站设定,主要包括创建数据库,设置网站的nginx配置和复制wp-config.php(基于wordpress)。

class blog {

  $db_user       = 'blog'
  $db_password   = 'blog'
  $db_name       = 'blog'

  $document_root = '/var/www/blog'
  $server_name   = 'xnnyygn.in'

  exec { 'create-database':
    path    => ['/bin', '/usr/bin'],
    unless  => "mysql -u$db_user -p$db_password $db_name",
    command => "mysql -uroot -p$mysql_root_password -e \"create database ${db_name}; grant all on ${db_name}.* to ${db_user}@localhost identified by '${db_password}';\"",
    require => Service['mysql'],
  }

  file { '/etc/nginx/sites-enabled/default':
    content => template('blog/nginx.conf.erb'),
    notify  => Service['nginx'],
  }

  file { "${document_root}/wp-config.php":
    source => 'puppet:///modules/blog/wp-config.php'
  }

}

nginx.conf.erb的内容如下(/var/www/blog是wordpress的目录,全新的,未作任何修改):

server {

  listen 80;
  root <%= @document_root %>;
  server_name <%= @server_name %>;

  location / {
    index index.html index.htm index.php;
  }

  location ~ \.php$ {
    fastcgi_pass  unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include       fastcgi_params;
  }

}

wp_config.php基本上只改了数据库配置,这里就不放了。最后,执行puppet apply,一个网站瞬间就OK了,是不是很爽啊?

,