web服务之NGinx安装

系统和EPEL源的中nignx版本较旧,可以安装官方源的最新版本
官方包链接:

http://nginx.org/en/linux_packages.html

官方 yum 源链接

http://nginx.org/en/linux_packages.html#RHEL-CentOS

范例: 通过官方 yum 源安装nginx

[root@centos8 ~]# cat /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

范例:

#带有自动日志切割功能
[root@centos8 ~]# cat /etc/logrotate.d/nginx /var/log/nginx/*log {
    create 0664 nginx root
    daily
    rotate 10
    missingok
    notifempty
    compress
    sharedscripts
    postrotate
       /bin/kill -USR1 `cat /run/nginx.pid 2>/dev/null` 2>/dev/null || true
    endscript
}

使用安装完成的二进制文件nginx

[root@centos8 ~]# nginx -h
nginx version: nginx/1.18.0
Usage: nginx [-?hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives]
Options:
-?,-h : this help
-v : show version and exit
-V : show version and configure options then exit #显示版本和编译参数
-t : test configuration and exit #测试配置文件是否异
常
-T : test configuration, dump it and exit #测试并打印
-q : suppress non-error messages during configuration testing #静默模
式
-s signal : send signal to a master process: stop, quit, reopen, reload #发
送信号,reload信号 会生成新的worker,但master不会重新生成
-p prefix : set prefix path (default: /etc/nginx/)
#指定Nginx 目录
-c filename : set configuration file (default: /etc/nginx/nginx.conf)
#配置文件路径
-g directives : set global directives out of configuration file#设置全局指令,注意
和配置文件不要同时配置,否则冲突

yum安装的验证 Nginx

[root@localhost ~]# nginx -V
nginx version: nginx/1.14.1
built by gcc 8.2.1 20180905 (Red Hat 8.2.1-3) (GCC)
built with OpenSSL 1.1.1 FIPS  11 Sep 2018 (running with OpenSSL 1.1.1c FIPS  28 May 2019)
TLS SNI support enabled
configure arguments: --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --pid-path=/run/nginx.pid --lock-path=/run/lock/subsys/nginx --user=nginx --group=nginx --with-file-aio --with-ipv6 --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_addition_module --with-http_xslt_module=dynamic --with-http_image_filter_module=dynamic --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_degradation_module --with-http_slice_module --with-http_stub_status_module --with-http_perl_module=dynamic --with-http_auth_request_module --with-mail=dynamic --with-mail_ssl_module --with-pcre --with-pcre-jit --with-stream=dynamic --with-stream_ssl_module --with-debug --with-cc-opt='-O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1 -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -specs=/usr/lib/rpm/redhat/redhat-hardened-ld -Wl,-E'

范例:Nginx 启动文件

[root@centos8 ~]# cat /usr/lib/systemd/system/nginx.service
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target
[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID
[Install]
WantedBy=multi-user.target

Nginx 编译安装

编译器介绍

源码安装需要提前准备标准的编译器,GCC的全称是(GNU Compiler collection),其有GNU开发,并以
GPL即LGPL许可,是自由的类UNIX即苹果电脑Mac OS X操作系统的标准编译器,因为GCC原本只能处理C语
言,所以原名为GNU C语言编译器,后来得到快速发展,可以处理C++,Fortran,pascal,objective-
C,java以及Ada等其他语言,此外还需要Automake工具,以完成自动创建Makefile的工作,Nginx的一些
模块需要依赖第三方库,比如: pcre(支持rewrite),zlib(支持gzip模块)和openssl(支持ssl模
块)等。

官方源码包下载地址:

https://nginx.org/en/download.html

范例: 编译安装

[root@centos8 ~]# yum -y install gcc pcre-devel openssl-devel zlib-devel

[root@centos8 ~]# useradd -s /sbin/nologin nginx
[root@centos8 ~]# cd /usr/local/src/
[root@centos8 src]# wget http://nginx.org/download/nginx-1.18.0.tar.gz
[root@centos8 src]# tar xf nginx-1.18.0.tar.gz
[root@centos8 src]# cd nginx-1.18.0/
[root@centos8 nginx-1.18.0]#./configure --prefix=/apps/nginx 
--user=nginx 
--group=nginx 
--with-http_ssl_module 
--with-http_v2_module 
--with-http_realip_module 
--with-http_stub_status_module 
--with-http_gzip_static_module 
--with-pcre 
--with-stream 
--with-stream_ssl_module 
--with-stream_realip_module

[root@centos8 nginx-1.18.0]# make && make install
#修改权限
[root@centos8 nginx-1.18.0]# chown -R nginx.nginx /apps/nginx

#生成目录如下:
[root@centos8 nginx-1.18.0]#ll /apps/nginx/
total 0
drwxr-xr-x 2 root root 333 Sep 22 18:49 conf
drwxr-xr-x 2 root root 40 Sep 22 18:49 html
drwxr-xr-x 2 root root 6 Sep 22 18:49 logs
drwxr-xr-x 2 root root 19 Sep 22 18:49 sbin
conf:保存nginx所有的配置文件,其中nginx.conf是nginx服务器的最核心最主要的配置文件,其他
的.conf则是用来配置nginx相关的功能的,例如fastcgi功能使用的是fastcgi.conf和
fastcgi_params两个文件,配置文件一般都有个样板配置文件,是文件名.default结尾,使用的使用将其
复制为并将default去掉即可。
html目录中保存了nginx服务器的web文件,但是可以更改为其他目录保存web文件,另外还有一个50x的web
文件是默认的错误页面提示页面。
logs:用来保存nginx服务器的访问日志错误日志等日志,logs目录可以放在其他路径,比
如/var/logs/nginx里面。
sbin:保存nginx二进制启动脚本,可以接受不同的参数以实现不同的功能。

范例:创建 Nginx 自启动文件

#复制同一版本的nginx的yum安装生成的service文件
[root@centos8 ~]# vim /usr/lib/systemd/system/nginx.service
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target
[Service]
Type=forking
PIDFile=/apps/nginx/run/nginx.pid
ExecStart=/apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID
[Install]
WantedBy=multi-user.target

#创建目录
[root@centos8 ~]# mkdir /apps/nginx/run/

#修改配置文件
[root@centos8 ~]# vim /apps/nginx/conf/nginx.conf
pid /apps/nginx/run/nginx.pid;

验证 Nginx 自启动文件
[root@centos8 ~]# systemctl daemon-reload
[root@centos8 ~]# systemctl enable --now nginx

案例:一键安装nginx脚本

[root@sz-kx-centos8 ~]# cat install_nginx.sh 
#!/bin/bash
#
#********************************************************************
#Author:		xuanlv
#QQ: 		    360956175
#Date: 			2021-06-09
#FileName:		install_nginx.sh
#URL: 			https://www.cnblogs.com/xuanlv-0413/
#Description:		The test script
#Copyright (C): 	2021 All rights reserved
#********************************************************************

NGINX_URL=http://nginx.org/download/
NGINX_FILE=nginx-1.18.0
TAR=.tar.gz
SRC_DIR=/usr/local/src/
NGINX_INSTALL_DIR=/apps/nginx
CPUS=`lscpu | awk '/^CPU(s)/{print $2}'`
GREEND="echo -e E[1;32m"
RED="echo -e E[1;31m"
END="E[0m"

os_type(){
   awk -F'[ "]' '/^NAME/{print $2}' /etc/os-release
}

os_version(){
  awk -F'"' '/^VERSION_ID/{print $2}' /etc/os-release
}

check(){
  [ -e ${NGINX_INSTALL_DIR} ] && { ${GREEND} "nginx 已安装,请卸载后再安装"${END}; exit; }
  cd ${SRC_DIR}
  if [ -e ${NGINX_FILE}${TAR} ];then
     ${GREEND}"相关文件已准备好"${END}
  else 
     ${GREEND}"开始下载nginx源码包"${END}
     if rpm -q wget &> /dev/null || yum install -y wget &> /dev/null
     then
        wget ${NGINX_URL}${NGINX_FILE}${TAR} &> /dev/null
        [ -f ${SRC_DIR}${NGINX_FILE}${TAR} ] && ${GREEND}"nginx源码包下载成功!"${END} || { ${RED}"下载 ${NGINX_FILE}${TAR}文件失败"${END}; exit; }
     else   
        dpkg -s wget &> /dev/null || apt install -y wget 
        wget ${NGINX_URL}${NGINX_FILE}${TAR} &> /dev/null
        [ -f ${SRC_DIR}${NGINX_FILE}${TAR} ] && ${GREEND}"nginx源码包下载成功!"${END} || { ${RED}"下载 ${NGINX_FILE}${TAR}文件失败"${END}; exit; }
     fi
     [ $? -ne 0 ] && { ${RED}"下载 ${NGINX_FILE}${TAR}文件失败"${END}; exit; }
  fi
}
install_nginx(){
  ${GREEND}"开始安装nginx"${END}
  if id nginx &> /dev/null;then
      ${GREEND}"nginx用户已存在"${END}
  else
      useradd -s /sbin/nologin -r nginx
      ${GREEND}"创建nginx用户"${END}
  fi
  ${GREEND}"开始安装nginx依赖包"${END}
  if [ `os_type` == "CentOS" -a `os_version` == '8' ];then
       yum -q install -y make gcc-c++ libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel perl-ExtUtils-Embed
  elif [ `os_type` == "CentOS" -a `os_version` == '7' ];then
       yum -q install -y make gcc pcre-devel openssl-devel zlib-devel perl-ExtUtils-Embed
  else
       apt update &> /dev/null
       apt -y install make gcc libpcre3 libpcre3-dev openssl libssl-dev zlib1g-dev &> /dev/null
  fi
  cd $SRC_DIR
  tar xf ${NGINX_FILE}${TAR}
  NGINX_DIR=`echo ${NGINX_FILE}${TAR}| sed -nr 's/^(.*[0-9]).*/1/p'`
  cd ${NGINX_DIR}
  ./configure --prefix=${NGINX_INSTALL_DIR} 
  --user=nginx 
  --group=nginx 
  --with-http_ssl_module 
  --with-http_v2_module 
  --with-http_realip_module 
  --with-http_stub_status_module 
  --with-http_gzip_static_module 
  --with-pcre --with-stream 
  --with-stream_ssl_module 
  --with-stream_realip_module
  make -j ${CPUS} && make install
  [ $? -eq 0 ] && ${GREEND}"nginx编译安装成功"${END} || { ${RED}"nginx编译安装失败,退出"${END}; exit; }
  cat > /etc/profile.d/nginx.sh <<EOF
#!/bin/bash
PATH=${NGINX_INSTALL_DIR}/sbin:${PATH}
EOF
  [ $? -eq 0 ] && source /etc/profile.d/nginx.sh
  cat > /lib/systemd/system/nginx.service <<-EOF
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=${NGINX_INSTALL_DIR}/logs/nginx.pid
ExecStartPre=/bin/rm -f ${NGINX_INSTALL_DIR}/logs/nginx.pid
ExecStartPre=${NGINX_INSTALL_DIR}/sbin/nginx -t
ExecStart=${NGINX_INSTALL_DIR}/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF

  systemctl daemon-reload
  systemctl enable --now nginx &> /dev/null
  systemctl is-active nginx &> /dev/null || { ${RED}"nginx启动失败,退出"${END}; exit; }
  ${GREEND}"nginx安装完成!!!"${END}
}

main(){
check
install_nginx
}
main

利用 ansible 的roles 实现 nginx 编译安装

注意:如果需要安装第三方包最好换个路径,不然ansible执行会报错,自己挖的坑,自己承受吧。(编译添加第三方包这里不演示了,因为全部的路径都要改) 这个roles需要有基础的,零基础不建议看

在编译NGINX时需要第三方包的加入下面两条命令:
--add-module=/xxx/ansible/roles/nginx/meta/echo-nginx-module 
--add-module=/xxx/ansible/roles/nginx/meta/ngx_cache_purge 

# 下载第三包
[root@sz-kx-centos8 ~]# yum install git -y
[root@sz-kx-centos8 ~]# git clone https://github.com/openresty/echo-nginx-module.git
[root@sz-kx-centos8 ~]# git clone https://github.com/FRiCKLE/ngx_cache_purge.git

# 本次roles整个结构如下:
[root@sz-kx-centos8 /etc/ansible/roles]# tree nginx/ -L 2
nginx/
├── files
│   ├── GeoIP-1.6.12.tar.gz
│   ├── nginx-1.18.0.tar.gz
│   ├── openssl-1.1.1k.tar.gz
│   ├── pcre-8.44.tar.gz
│   └── zlib-1.2.11.tar.gz
├── handlers
│   └── main.yml
├── meta
│   ├── echo-nginx-module
│   └── ngx_cache_purge
├── tasks
│   ├── config.yml
│   ├── group.yml
│   ├── install_package.yml
│   ├── install.yml
│   ├── main.yml
│   ├── service.yml
│   ├── start.yml
│   ├── unarchive.yml
│   └── user.yml
├── templates
│   ├── nginx.conf.j2
│   └── nginx.service.j2
└── vars
    └── main.yml

8 directories, 18 files

定义变量

[root@sz-kx-centos8 ~]# cat /etc/ansible/roles/nginx/vars/main.yml
app_dir: /apps/nginx
src_dir: /usr/local/src
nginx_version: nginx-1.18.0
openssl_version: openssl-1.1.1k
pcre_version: pcre-8.44
zlib_version: zlib-1.2.11
geoip_version: GeoIP-1.6.12
tar_type: .tar.gz
group_name: nginx
user_name: nginx
uid: 80
gid: 80
centos7_packages: [ make,gcc-c++,pcre-devel,openssl-devel,zlib-devel,perl-ExtUtils-Embed ]
centos8_packages: [ make,gcc-c++,libtool,pcre,pcre-devel,zlib,zlib-devel,openssl,openssl-devel,perl-ExtUtils-Embed ]
ubuntu_packages: [ make,gcc,libpcre3,libpcre3-dev,openssl,libssl-dev,zlib1g-dev,libapr1-dev,libaprutil1-dev,libgeoip-dev,build-essential,gzip,bzip2,libtool ]

定义模板配置文件

[root@sz-kx-centos8 ~]# cat /etc/ansible/roles/nginx/templates/nginx.conf.j2
user {{ user_name }};
worker_processes {{ ansible_processor_vcpus }};
error_log {{ app_dir }}/logs/error.log;
pid {{ app_dir }}/run/nginx.pid;

include {{ app_dir }}/conf.d/*.conf;

events {
    worker_connections 65535;
}

http {
    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  {{ app_dir }}/logs/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             mime.types;
    default_type        application/octet-stream;

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        location / {
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

}

定义启动文件

[root@sz-kx-centos8 ~]# cat /etc/ansible/roles/nginx/templates/nginx.service.j2
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile={{ app_dir }}/run/nginx.pid
ExecStartPre=/bin/rm -f {{ app_dir }}/run/nginx.pid
ExecStartPre={{ app_dir }}/sbin/nginx -t
ExecStart={{ app_dir }}/sbin/nginx
ExecReload=/bin/kill -s HUP {{ app_dir }}/run/nginx.pid
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true

[Install]
WantedBy=multi-user.target

编写 handler 文件

[root@sz-kx-centos8 ~]# cat /etc/ansible/roles/nginx/handlers/main.yml
---
- name: restart Nginx
  service: name=nginx state=restarted

- debug: msg="nginx start successfull"

定义任务的执行顺序

[root@sz-kx-centos8 ~]# cat /etc/ansible/roles/nginx/tasks/main.yml
- include: install_package.yml
- include: group.yml
- include: user.yml
- include: unarchive.yml
- include: install.yml
- include: config.yml
- include: service.yml
- include: start.yml

按系统安装依赖包

[root@sz-kx-centos8 ~]# cat /etc/ansible/roles/nginx/tasks/install_package.yml
- name: yum nginx packages to centos7
  yum: name={{ centos7_packages }}
  when: ansible_distribution_major_version == "7"

- name: yum nginx packages to centos8
  yum: name={{ centos8_packages }}
  when: ansible_distribution_major_version == "8"

- name: apt nginx packages to ubuntu
  apt: name={{ ubuntu_packages }}
  when: ansible_os_family == "Debian"

创建组

[root@sz-kx-centos8 ~]# cat /etc/ansible/roles/nginx/tasks/group.yml
---
- name: delete {{ app_dir }}
  file: path={{ app_dir }} state=absent
  ignore_errors: True

- name: create {{ app_dir }}
  file: path={{ app_dir }} state=directory owner=root group=root mode=755

- name: create group
  group: name={{ group_name }} gid={{ gid }} system=yes
  ignore_errors: True

创建用户

[root@sz-kx-centos8 ~]# cat /etc/ansible/roles/nginx/tasks/user.yml
---
- name: create user
  user: name={{ user_name }} uid={{ uid }} group={{ group_name  }} shell=/sbin/nologin system=yes create_home=no home={{ app_dir }}/conf/nginx
  ignore_errors: True

解包

[root@sz-kx-centos8 ~]# cat /etc/ansible/roles/nginx/tasks/unarchive.yml
---
- name: delete {{ src_dir }}
  file: path={{ src_dir }} state=absent
  ignore_errors: True

- name: create {{ src_dir }}
  file: path={{ src_dir }} state=directory owner=root group=root mode=755

- name: unarchive geoip file
  unarchive: src="files/{{ geoip_version }}{{ tar_type }}" dest={{ src_dir }} owner=root remote_src=no

- name: unarchive pcre file
  unarchive: src="files/{{ pcre_version }}{{ tar_type }}" dest={{ src_dir }} owner=root remote_src=no

- name: unarchive zlib file
  unarchive: src="files/{{ zlib_version }}{{ tar_type }}" dest={{ src_dir }} owner=root remote_src=no

- name: unarchive openssl file
  unarchive: src="files/{{ openssl_version }}{{ tar_type }}" dest={{ src_dir }} owner=root remote_src=no

- name: unarchive nginx file
  unarchive: src="files/{{ nginx_version }}{{ tar_type }}" dest={{ src_dir }} owner=root remote_src=no

- name: build geoip
  shell: chdir={{ src_dir }}/{{ geoip_version }} ./configure &&  make -j {{ ansible_processor_vcpus }} && make install

编译安装NGINX

[root@sz-kx-centos8 ~]# cat /etc/ansible/roles/nginx/tasks/install.yml
- name: configure nginx
  shell:
    chdir={{ src_dir }}/{{ nginx_version }} 
    ./configure 
    --prefix={{ app_dir }} 
    --user={{ user_name }} 
    --group={{ group_name }} 
    --sbin-path={{ app_dir }}/sbin/nginx 
    --conf-path={{ app_dir }}/conf/nginx.conf 
    --pid-path={{ app_dir }}/run/nginx.pid 
    --with-http_auth_request_module 
    --with-http_realip_module 
    --with-http_v2_module 
    --with-debug 
    --with-http_random_index_module 
    --with-http_sub_module 
    --with-http_addition_module 
    --with-http_secure_link_module 
    --with-http_geoip_module 
    --with-http_ssl_module 
    --with-stream_ssl_module 
    --with-stream_realip_module 
    --with-stream_ssl_preread_module 
    --with-stream 
    --with-http_slice_module 
    --with-threads 
    --with-http_gzip_static_module 
    --with-http_gunzip_module 
    --with-http_stub_status_module 
    --with-file-aio 
    --with-pcre={{ src_dir }}/{{ pcre_version }}  
    --with-zlib={{ src_dir }}/{{ zlib_version }} 
    --with-openssl={{ src_dir }}/{{ openssl_version }}

- name: install nginx
  shell:
    chdir={{ src_dir }}/{{ nginx_version }} make -j {{ ansible_processor_vcpus }} && make install

- debug: msg="nginx install successfull"

copy配置文件

[root@sz-kx-centos8 ~]# cat /etc/ansible/roles/nginx/tasks/config.yml
- name: template config to remote hosts
  template: src=nginx.conf.j2 dest={{ app_dir }}/conf/nginx.conf
  notify:
    - restart Nginx

copy启动文件

[root@sz-kx-centos8 ~]# cat /etc/ansible/roles/nginx/tasks/service.yml
---
- name: set lib
  shell: echo "/usr/local/lib" >> /etc/ld.so.conf && ldconfig

- name: set nginx to profile PATH
  shell: echo PATH={{ app_dir }}/sbin:$PATH > /etc/profile.d/nginx.sh

- name: copy nginx.service to centos
  template: src=nginx.service.j2 dest=/usr/lib/systemd/system/nginx.service
  notify: restart Nginx
  when: ansible_os_family == "RedHat"

- name: copy nginx.service to ubuntu
  template: src=nginx.service.j2 dest=/lib/systemd/system/nginx.service
  notify: restart Nginx
  when: ansible_os_family == "Debian"

- name: reload systemd manager configuration
  shell: systemctl daemon-reload

启动NGINX

[root@sz-kx-centos8 ~]# cat /etc/ansible/roles/nginx/tasks/start.yml
- name: start nginx.service
  service: name=nginx state=started enabled=yes

- debug: msg="nginx start succesfull"

启用某个主机组作为roles角色

[root@sz-kx-centos8 ~]# cat /etc/ansible/roles/install_nginx.yml
---
- hosts: webser
  remote_user: root
  roles:
    - nginx

切换到roles目录下

[root@sz-kx-centos8 ~]# cd /etc/ansible/roles/
[root@sz-kx-centos8 /etc/ansible/roles]# ls
install_nginx.yml  nginx
[root@sz-kx-centos8 /etc/ansible/roles]# pwd
/etc/ansible/roles

检查配置(这里检查不会解包,执行过程会报错)

[root@sz-kx-centos8 /etc/ansible/roles]# ansible-playbook -C install_nginx.yml

执行

[root@sz-kx-centos8 /etc/ansible/roles]# ansible-playbook install_nginx.yml

这步可以使用ansible的shell模块远程检查端口80是否已经打开

[root@sz-kx-centos8 /etc/ansible/roles]# ansible webser -m shell -a "ss -tnlp | grep 80"
172.31.0.28 | CHANGED | rc=0 >>
LISTEN   0         128                 0.0.0.0:80               0.0.0.0:*        users:(("nginx",pid=7474,fd=8),("nginx",pid=7473,fd=8),("nginx",pid=7472,fd=8))
LISTEN   0         128                    [::]:80                  [::]:*        users:(("nginx",pid=7474,fd=9),("nginx",pid=7473,fd=9),("nginx",pid=7472,fd=9))
172.31.0.29 | CHANGED | rc=0 >>
LISTEN   0         128                 0.0.0.0:80               0.0.0.0:*        users:(("nginx",pid=109659,fd=6),("nginx",pid=109658,fd=6),("nginx",pid=109657,fd=6))
LISTEN   0         128                    [::]:80                  [::]:*        users:(("nginx",pid=109659,fd=7),("nginx",pid=109658,fd=7),("nginx",pid=109657,fd=7))
172.31.0.17 | CHANGED | rc=0 >>
LISTEN     0      128          *:80                       *:*                   users:(("nginx",pid=57124,fd=6),("nginx",pid=57123,fd=6),("nginx",pid=57122,fd=6))
LISTEN     0      128         :::80                      :::*                   users:(("nginx",pid=57124,fd=7),("nginx",pid=57123,fd=7),("nginx",pid=57122,fd=7))

报错:

编译时报错:"./configure: error: no /etc/ansible/roles/nginx/meta/echo-nginx-module/config was found"]},,原因是找不到这个包???

解决方法:1)编译安装NGINX时不要加这两个进去编译:

--add-module=/xxx/ansible/roles/nginx/meta/echo-nginx-module 
--add-module=/xxx/ansible/roles/nginx/meta/ngx_cache_purge 

2)如果真需要这第三方包的,目前不确定原因,据说是因为/etc/ansible报错,重新做一个roles角色路径吧。。。

原文地址:https://www.cnblogs.com/xuanlv-0413/p/14905029.html