tee deploy_nginx.yml <<EOF
---
- name: 源码包部署 Nginx
hosts: webservers # 替换为你的 Web 服务器组名
become: true # 需要 root 权限
tasks:
# 安装编译依赖
- name: 安装编译依赖
yum:
name:
- gcc
- pcre-devel
- zlib-devel
- openssl-devel
state: present
# 创建 Nginx 用户
- name: 创建 Nginx 用户
user:
name: nginx
shell: /sbin/nologin
create_home: false
state: present
# 下载并解压 Nginx 源码包
- name: 下载 Nginx 源码包
get_url:
url: http://nginx.org/download/nginx-1.26.2.tar.gz
dest: /tmp/nginx-1.26.2.tar.gz
- name: 解压 Nginx 源码包
unarchive:
src: /tmp/nginx-1.26.2.tar.gz
dest: /tmp/
remote_src: true
# 配置、编译和安装 Nginx
- name: 配置 Nginx
command: ./configure --prefix=/usr/local/nginx-1.26.2 --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_stub_status_module --with-stream
args:
chdir: /tmp/nginx-1.26.2
- name: 编译 Nginx
command: make
args:
chdir: /tmp/nginx-1.26.2
- name: 安装 Nginx
command: make install
args:
chdir: /tmp/nginx-1.26.2
- name: 创建 Nginx 软连接
file:
src: /usr/local/nginx-1.26.2
dest: /usr/local/nginx
state: link
owner: nginx
group: nginx
# 创建 Nginx 工作目录
- name: 创建 Nginx 目录
file:
path: "{{ item }}"
state: directory
mode: '0755'
loop:
- /usr/local/nginx
- /usr/local/nginx/conf
- /usr/local/nginx/logs
- /usr/local/nginx/html
- name: 设置 Nginx 目录权限
file:
path: /usr/local/nginx-1.26.2
owner: nginx
group: nginx
recurse: true
# 配置 Nginx 服务
- name: 创建 Nginx 服务文件
copy:
content: |
[Unit]
Description=The NGINX HTTP Server
After=syslog.target network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
dest: /usr/lib/systemd/system/nginx.service
mode: '0644'
- name: 创建 Nginx 默认首页
copy:
content: |
www
dest: /usr/local/nginx/html/index.html
mode: '0644'
- name: 重载 systemd
systemd:
daemon_reload: true
- name: 启动并启用 Nginx
service:
name: nginx
state: started
enabled: true
# 验证 Nginx 安装
- name: 检查 Nginx 版本
command: /usr/local/nginx/sbin/nginx -v
register: nginx_version
changed_when: false
- name: 显示 Nginx 版本
debug:
msg: "Nginx 版本: {{ nginx_version.stderr }}"
- name: 检查 Nginx 服务状态
command: systemctl is-active nginx
register: nginx_status
changed_when: false
- name: 显示 Nginx 服务状态
debug:
msg: "Nginx 服务状态: {{ nginx_status.stdout }}"
EOF