原始整理页:http://liujixiang.dpdns.org:10092/projects/ansible-lnmp.html
- 项目类型:Ansible 自动化部署
- 支持平台:RedHat 系 / Debian 系
- 部署服务:Nginx + PHP-FPM + MariaDB
- 来源页面更新时间:2024-11-18
多服务器部署LNMP环境时,Red Hat系和Debian系有部分差异
比如php-fpm路径
Red Hat系:/run/php-fpm/www.sock
Debian系:/run/php/php-fpm.sock
1.我在编写此ansible剧本时,遇到的最大问题就是启动php-fpm时找不到服务名
Red Hat系只需要
- name: Enable and Start PHP-FPM
service:
name: php-fpm
state: started
enabled: yes
而Debian系必须在name的php-fpm中指定版本号,而我们是先安装的php-fpm,后设置的启动和开机自启,所以可以模糊查找现有的fpm-fpm版本
- name: Find actual PHP-FPM service name
#识别所装的php-fpm版本,并赋值给变量 detected_php_fpm_service
shell: systemctl list-unit-files | grep -E '^php.*fpm\.service' | head -1 | cut -d' ' -f1 | sed 's/\.service$//'
register: detected_php_fpm_service
changed_when: false
- name: Enable and Start PHP-FPM
service:
name: "{{ detected_php_fpm_service.stdout }}"
state: started
enabled: yes
2.被我忽略socket路径问题
在- name: Deploy Nginx LNMP config模块中
fastcgi_pass unix:{{ php_fmp_socket }};大括号两边不能有双引号
只有像root "{{ web_root }}";这种变量为路径的才用双引号才没事
nginx的fastcgi_pass指令解析逻辑:
- 看到unix:前缀 → 识别为Unix socket
- 看到”unix:”字符串 → 当作TCP地址,尝试DNS解析失败
3.剩下的主要差异都在变量定义中
PHP的数据库连接驱动
Red Hat系:php-mysqlnd
Debian系:php-mysql
Python的数据库连接库
Red Hat系:python3-PyMySQL
Debian系:python3-pymysql
group和owner归属
Red Hat系:nginx
Debian系:www-data
4.完整剧本实现
只需更改hosts: 你要部署的主机组和”#数据库配置变量”下的变量即可使用
---
- name: LNMP
hosts: 你要部署的主机组
become: yes
vars:
web_root: /var/www/html
php_fpm_socket: "{{ php_sockets[ansible_facts['os_family']] | default('/run/php-fmp/www.sock') }}"
nginx_user: "{{ 'nginx' if ansible_facts['os_family'] == 'RedHat' else 'www-data' }}"
#数据库配置变量
mysql_root_password: "你的数据库root密码"
site_db_name: "你要创建的数据库名称"
site_db_user: "你的数据库用户名"
site_db_password: "你的数据库密码"
packages_redhat:
- nginx
- mariadb-server
- php
- php-fpm
- php-mysqlnd
- python3-PyMySQL
packages_debian:
- nginx
- mariadb-server
- php
- php-fmp
- php-mysql
- python3-pymysql
php_sockets:
RedHat: /run/php-fmp/www.sock
Debian: /run/php/php-fmp.sock
mysql_socket:
RedHat: /var/lib/mysql/mysql.sock
Debian: /run/mysqld/mysqld.sock
tasks:
#设置PHP-FPM socket路径
- name: Set PHP-FPM socket path
set_fact:
php_fpm_socket: "{{ php_sockets[ansible_facts['os_family']] }}"
#获取本机公网ip以显示在数据库信息展示页面
- name: Get public IP address
uri:
url: http://ifconfig.me
return_content: yes
register: public_ip_result
ignore_errors: yes
- name: Set public IP fact
set_fact:
public_ip: "{{ public_ip_result.content | trim if public_ip_result is succeeded and public_ip_result.content is defined else ansible_default_ipv4.address }}"
- name: Install packages (RedHat)
package:
name: "{{ packages_redhat }}"
state: present
when: ansible_facts['os_family'] == 'RedHat'
- name: Install packages (Debian)
package:
name: "{{ packages_debian }}"
state: present
when: ansible_facts['os_family'] == 'Debian'
#确保站点根目录
- name: Ensure web root exists
file:
path: "{{ web_root }}"
state: directory
owner: "{{ nginx_user }}"
group: "{{ nginx_user }}"
mode: '0755'
#删除默认站点(避免冲突)
- name: Remove default nginx site
file:
path: /etc/nginx/conf.d/default.conf
state: absent
#确保index.php可以被访问
- name: Deploy php test page
copy:
dest: "{{ web_root }}/index.php"
content: |
<?php
//PHP 信息页面
echo "<h1>LNMP Stack Status</h1>";
echo "<h2>PHP Version: " . phpversion() . "</h2>";
//测试数据库连接
$host = 'localhost';
$db = '{{ site_db_name }}';
$user = '{{ site_db_user }}';
$pass = '{{ site_db_password }}';
try {
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "<h3 style='color:green;'>Database Connection SUCCESS</h3>";
echo "<p>Connected to database: <strong>$db</strong></p>";
} catch(PDOException $e) {
echo "<h3 style='color:red'>Database Connection: FAILED</h3>";
echo "<p>Error: " . $e->getMessage() . "</p>";
}
echo "<hr>";
echo "<h2>Full PHP Info:</h2>";
phpinfo();
?>
owner: "{{ nginx_user }}"
group: "{{ nginx_user }}"
mode: '0664'
#部署nginx配置 PS: fastcgi_pass unix:{{ php_fmp_socket }};大括号两边不能加"",会导致寻找不到路径,连接PHP-FPM失败
- name: Deploy Nginx LNMP config
copy:
dest: /etc/nginx/conf.d/lnmp.conf
mode: '0644'
content: |
server {
listen 80;
server_name _;
root "{{ web_root }}";
index index.php index.html;
#日志配置
access_log /var/log/nginx/lnmp_access.log;
error_log /var/log/nginx/lnmp_error.log;
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass unix:{{ php_fmp_socket }};
fastcgi_index index.php;
include fastcgi.conf;
}
#禁止访问隐藏文件
location ~ /\. {
deny all;
}
}
notify: Reload Nginx
#开机自启配置
- name: Enable and Start Nginx
service:
name: nginx
state: started
enabled: yes
#寻找php-fmp的完整服务名(与红帽系统不同,debian系统需要写完整php-fmp的版本名)
- name: Find actual PHP-FPM service name
shell: systemctl list-unit-files | grep -E '^php.*fmp\.service' | head -1 | cut -d' ' -f1 | sed 's/\.service$//'
register: detected_php_fpm_service
changed_when: false
- name: Enable and Start PHP-FPM
service:
name: "{{ detected_php_fpm_service.stdout }}"
state: started
enabled: yes
- name: Enable and Start MariaDB
service:
name: mariadb
state: started
enabled: yes
- name: Set MariaDB root password
mysql_user:
name: root
password: "{{ mysql_root_password }}"
host_all: yes
login_unix_socket: "{{ mysql_socket[ansible_facts['os_family']] }}"
state: present
#若已设置密码会报错,忽略
ignore_errors: yes
#删除匿名用户
- name: Remove anonymous MySQL users
mysql_user:
name: ''
host_all: yes
state: absent
login_user: root
login_password: "{{ mysql_root_password }}"
login_unix_socket: "{{ mysql_socket[ansible_facts['os_family']] }}"
#删除测试数据库
- name: Remove MySQL test database
mysql_db:
name: test
state: absent
login_user: root
login_password: "{{ mysql_root_password }}"
login_unix_socket: "{{ mysql_socket[ansible_facts['os_family']] }}"
#创建应用数据库
- name: Create site database
mysql_db:
name: "{{ site_db_name }}"
state: present
encoding: utf8mb4
collation: utf8mb4_general_ci
login_user: root
login_password: "{{ mysql_root_password }}"
login_unix_socket: "{{ mysql_socket[ansible_facts['os_family']] }}"
- name: Create site database user
mysql_user:
name: "{{ site_db_user }}"
password: "{{ site_db_password }}"
priv: "{{ site_db_name }}.*:ALL"
host: localhost
state: present
login_user: root
login_password: "{{ mysql_root_password }}"
login_unix_socket: "{{ mysql_socket[ansible_facts['os_family']] }}"
#检查nginx配置
- name: Validate nginx configuration
command: nginx -t
register: nginx_check
changed_when: false
- name: Nginx Check
debug:
var: nginx_check.stdout
#显示数据库信息
- name: Display database credentials
debug:
msg:
- "=============================================="
- "LNMP Stack Deployed Successfully!"
- "=============================================="
- "Web Root: {{ web_root }}"
- "Database Name: {{ site_db_name }}"
- "Database User: {{ site_db_user }}"
- "Database Password: {{ site_db_password }}"
- "MySQL Root Password: {{ mysql_root_password }}"
- "=============================================="
- "Access your site: http://{{ public_ip }}"
- "=============================================="
handlers:
- name: Reload Nginx
service:
name: nginx
state: reloaded