---
- hosts: localhost
become: yes
vars:
nginx_version: "1.22.0"
nginx_install_dir: "/usr/local/nginx"
nginx_source_dir: "/tmp/nginx-{{ nginx_version }}"
nginx_service_file: |
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile={{ nginx_install_dir }}/logs/nginx.pid
ExecStartPre={{ nginx_install_dir }}/sbin/nginx -t -c {{ nginx_install_dir }}/conf/nginx.conf
ExecStart={{ nginx_install_dir }}/sbin/nginx -c {{ nginx_install_dir }}/conf/nginx.conf
ExecReload={{ nginx_install_dir }}/sbin/nginx -s reload
ExecStop={{ nginx_install_dir }}/sbin/nginx -s stop
PrivateTmp=true
[Install]
WantedBy=multi-user.target
tasks:
- name: 安装编译依赖
yum:
name:
- gcc
- gcc-c++
- pcre
- pcre-devel
- zlib-devel
- make
- openssl
- openssl-devel
- gd
- gd-devel
- zlib
- zlib-devel
- geoip-devel
state: present
- name: 下载 Nginx 源码
get_url:
url: "http://nginx.org/download/nginx-{{ nginx_version }}.tar.gz"
dest: "/tmp/nginx-{{ nginx_version }}.tar.gz"
- name: 解压 Nginx 源码
unarchive:
src: "/tmp/nginx-{{ nginx_version }}.tar.gz"
dest: "/tmp/"
remote_src: yes
- name: 创建 nginx 组
group:
name: nginx
state: present
- name: 创建 nginx 用户
user:
name: nginx
group: nginx
state: present
system: yes
- name: 配置 Nginx
command: >
./configure
--prefix={{ nginx_install_dir }}
--user=nginx
--group=nginx
--with-pcre
--with-http_ssl_module
--with-http_v2_module
--with-http_realip_module
--with-http_addition_module
--with-http_sub_module
--with-http_dav_module
--with-http_flv_module
--with-http_mp4_module
--with-http_gunzip_module
--with-http_gzip_static_module
--with-http_random_index_module
--with-http_secure_link_module
--with-http_stub_status_module
--with-http_auth_request_module
--with-http_image_filter_module
--with-http_slice_module
--with-mail
--with-threads
--with-file-aio
--with-stream
--with-mail_ssl_module
--with-stream_ssl_module
--with-http_geoip_module
args:
chdir: "{{ nginx_source_dir }}"
- name: 编译 Nginx
command: make
args:
chdir: "{{ nginx_source_dir }}"
- name: 安装 Nginx
command: make install
args:
chdir: "{{ nginx_source_dir }}"
- name: 创建 Nginx systemd 服务文件
copy:
dest: /etc/systemd/system/nginx.service
content: "{{ nginx_service_file }}"
become: yes
- name: 重新加载 systemd 配置
systemd:
daemon_reload: yes
become: yes
- name: 启动并启用 Nginx 服务
systemd:
name: nginx
state: started
enabled: yes
become: yes
- name: 验证 Nginx 安装是否成功
command: "{{ nginx_install_dir }}/sbin/nginx -v"
register: nginx_version_check
changed_when: false
- name: 显示 Nginx 版本
debug:
msg: "{{ nginx_version_check.stdout }}"
10-22
1669
08-30
1645