欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 高考 > ansible自动化运维(四)运维实战

ansible自动化运维(四)运维实战

2025/11/11 11:44:22 来源:https://blog.csdn.net/2401_86247463/article/details/144424868  浏览:    关键词:ansible自动化运维(四)运维实战
 相关文章
ansible自动化运维(一)简介及清单,模块-CSDN博客
ansible自动化运维(二)playbook模式详解-CSDN博客
ansible自动化运维(三)jinja2模板&&roles角色管理-CSDN博客

五。运维实战

5.1Ansible自动化安装nginx

编译安装nginx

(1)下载nginx包

使用wget下载nginx包,下载地址:

http://mirrors.sohu.com/nginx/nginx-1.9.6.tar.gz

解压下载nginx包

[root@server ~]# wget http://mirrors.sohu.com/nginx/nginx-1.9.6.tar.gz

进入解压后的目录:

[root@server ~]# cd nginx-1.9.6

[root@server nginx-1.9.6]#

这条命令将当前工作目录切换到解压后的Nginx源代码目录。

安装两个依赖

[root@server nginx-1.9.6]# yum groupinstall "Development Tools" -y

[root@server nginx-1.9.6]# yum install pcre pcre-devel zlib zlib-devel openssl openssl-devel -y

配置编译参数:

[root@server nginx-1.9.6]# ./configure --prefix=/usr/local/nginx

 

这条命令运行configure脚本本来检查系统环境并生成Makefile。-prefix=/usr/local/nginx选项指定了安装路径,即Nginx将被安装到/usr/local/nginx目录下。

编译和安装

[root@server nginx-1.9.6]# make && make install

这两条命令依次执行以下操作:

make:根据Makefile中的规则编译源代码,生成可执行文件和其他必要的文件。

make install:将编译好的文件复制到指定的安装目录(由 --prefix 选项指定),即/usr/local/nginx

(2)编写/etc/init.d/nginx文件

[root@server nginx-1.9.6]# vi /etc/init.d/nginx

[root@server nginx-1.9.6]# chmod +x /etc/init.d/nginx

[root@server nginx-1.9.6]# cat /etc/init.d/nginx

#!/bin/bash

# chkconfig: - 30 21

# description: http service.

# Source Function Library

. /etc/init.d/functions

# Nginx Settings

NGINX_SBIN="/usr/local/nginx/sbin/nginx"

NGINX_CONF="/usr/local/nginx/conf/nginx.conf"

NGINX_PID="/usx/local/nginx/logs/nginx.pid"

RETVAL=0

prog="Nginx"

start()

{

        echo -n $"Starting $prog: "

        mkdir -p /dev/shm/nginx_temp

        daemon $NGINX_SBIN -c $NGINX_CONF

        RETVAL=$?

        echo

        return $RETVAL

}

stop()

{

        echo -n $"Stopping $prog: "

        killproc -p $NGINX_PID $NGINX_SBIN -TERM

        rm -rf /dev/shm/nginx_temp

        RETVAL=$?

        echo

        return $RETVAL

}

reload()

{

        echo -n $"Reloading $prog: "

        killproc -p $NGINX_PID $NGINX_SBIN -HUP

        RETVAL=$?

        echo

        return $RETVAL

}

restart()

{

        stop

        start

}

configtest()

{

        $NGINX_SBIN -c $NGINX_CONF -t

        return 0

}

case "$1" in

        start)

                start

                ;;

        stop)

                stop

                ;;

        reload)

                reload

                ;;

        restart)

                restart

                ;;

        configtest)

                configtest

                ;;

        *)

                echo $"Usage: $0 {start|stop|reload|restart|configtest}"

                RETVAL=1

esac

exit $RETVAL

 (3)清空配置文件重新填写

[root@server nginx-1.9.6]# vi /usr/local/nginx/conf/nginx.conf

[root@server nginx-1.9.6]# cat /usr/local/nginx/conf/nginx.conf

user nobody nobody;             #//定义nginx运行的用户和用户组

worker_processes 2;             #//nginx进程数,一般为CPU总核心数

error_log /usr/local/nginx/logs/nginx_error.log crit;   #//全局错误日志定义类型

pid /usr/local/nginx/logs/nginx.pid;    #//进程文件

worker_rlimit_nofile 51200;

events          #//工作模式与连接数上限

{

use epoll;

worker_connections 6000;

}

http            #//http下的一些配置

{

include mime.types;             #//文件扩展名与文件类型映射表

default_type application/octet-stream;          #//默认文件类型

server_names_hash_bucket_size 3526;

server_names_hash_max_size 4096;

log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]'

'$host "$request_uri" $status'

'"$http_referer" "$http_user_agent"';

sendfile on;            #//开启高效文件传输模式

tcp_nopush on;          #//防止网络阻塞

keepalive_timeout 30;           #//长连接超时时间,单位为秒

client_header_timeout 3m;

client_body_timeout 3m;

send_timeout 3m;

connection_pool_size 256;

client_header_buffer_size 1k;

large_client_header_buffers 8 4k;

request_pool_size 4k;

output_buffers 4 32k;

postpone_output 1460;

client_max_body_size 10m;

client_body_buffer_size 256k;

client_body_temp_path /usr/local/nginx/client_body_temp;

proxy_temp_path /usr/local/nginx/proxy_temp;

fastcgi_temp_path /usr/local/nginx/fastcgi_temp;

fastcgi_intercept_errors on;

tcp_nodelay on;         #//防止网络阻塞

gzip on;                #//开启gzip压缩输出

gzip_min_length 1k;

gzip_buffers 4 8k;

gzip_comp_level 5;

gzip_http_version 1.1;

gzip_types text/plain application/x-javascript text/css text/htm

application/xml;

server          #//虚拟主机配置

{

listen 80;

server_name localhost;

index index.html index.htm index.php;

root /usr/local/nginx/html;

location ~ \.php$

{

include fastcgi_params;

fastcgi_pass unix:/tmp/php-fcgi.sock;

fastcgi_index index.php;

fastcgi_param SCRIPT_FILENAME /usr/1ocal/nginx/html$fastcgi_script_name;

}

}

}

 

(4)编写完成后检查

[root@server nginx-1.9.6]# /usr/local/nginx/sbin/nginx -t

nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok

nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

(5)启动nginx

[root@server nginx-1.9.6]# service nginx start

Reloading systemd:                                         [  确定  ]

Starting nginx (via systemctl):                            [  确定  ]

 

编译安装完成

5.2环境准备 

(1)移动目录文件

将nginx.tar.gz复制到/etc/ansible/nginx_install/roles/install/files下

启动脚本和配置文件都放到/etc/ansible/nginx_install/roles/install/template下

[root@server ~]# mv nginx-1.9.6.tar.gz /etc/ansible/nginx_install/roles/install/files/

[root@server ~]# cp nginx-1.9.6/conf/nginx.conf /etc/ansible/nginx_install/roles/install/templates/

[root@server ~]# cp nginx-1.9.6/conf/nginx.conf /etc/ansible/nginx_install/roles/install/templates/

(2)编辑需要的yml文件 

[root@server nginx_install]# vi /etc/ansible/hosts    #清单文件中加入这两条

[nginx]

Host2

[root@server nginx_install]# cat install.yml

---

- hosts: nginx        #//入口文件

  remote_user: root

  gather_facts: True

  roles:

    - common

    - install

[root@server nginx_install]# cat roles/common/tasks/main.yml

- name: install initialization require software  #//安装需要的依赖

  yum: name={{ item }} state=installed

  with_items:

    - zlib-devel

    - pcre-devel

    - gcc

 

[root@server nginx_install]# cat roles/install/vars/main.yml

nginx_user: nobody        #//定义所需变量

nginx_port: 80

nginx_basedir: /usr/local/nginx

[root@server nginx_install]# cat roles/install/tasks/copy.yml

- name: Copy Nginx Software     #//复制压缩包

  copy: src=nginx-1.9.6.tar.gz dest=/tmp/nginx.tar.gz owner=root group=root

- name: Uncompression Nginx Software    #//解压压缩包

  shell: tar zxf /tmp/nginx.tar.gz -C /usr/local/

- name: install Nginx

  shell: cd /usr/local/nginx-1.9.6 && ./configure --prefix=/usr/local/nginx && make && make install

- name: Copy Nginx Start Script         #//复制启动脚本

  template: src=nginx dest=/etc/init.d/nginx owner=root group=root mode=0755

- name: Copy Nginx Config               #//复制nginx配置文件

  template: src=nginx.conf dest={{ nginx_basedir }}/conf/ owner=root group=root mode=0644

[root@server nginx_install]# cat roles/install/tasks/install.yml

- name: create nginx user       #//创建用户

  user: name={{ nginx_user }} state=present createhome=no shell=/sbin/nologin

- name: start nginx service     #//开启服务

  shell: /etc/init.d/nginx start

- name: add boot start nginx service    #//加入开机启动

  shell: chkconfig --level 345 nginx on

- name: delete nginx compression files  #//删除压缩包

  shell: rm -rf /tmp/nginx.tar.gz

[root@server nginx_install]# cat roles/install/tasks/main.yml

- include: copy.yml     #//调用copy.yml和install.yml

- include: install.yml

5.3执行文件

(1)运行install.yml

[root@server nginx_install]# ansible-playbook /etc/ansible/nginx_install/install.yml

[root@server nginx_install]# ansible-playbook /etc/ansible/nginx_install/install.yml

[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details

PLAY [nginx] *******************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************

ok: [host2]

TASK [common : install initialization require software] ************************************************************

[DEPRECATION WARNING]: Invoking "yum" only once while using a loop via squash_actions is deprecated. Instead of

using a loop to supply multiple items and specifying `name: "{{ item }}"`, please use `name: ['zlib-devel', 'pcre-

devel', 'gcc']` and remove the loop. This feature will be removed in version 2.11. Deprecation warnings can be

disabled by setting deprecation_warnings=False in ansible.cfg.

ok: [host2] => (item=[u'zlib-devel', u'pcre-devel', u'gcc'])

TASK [install : Copy Nginx Software] *******************************************************************************

ok: [host2]

TASK [install : Uncompression Nginx Software] **********************************************************************

[WARNING]: Consider using the unarchive module rather than running 'tar'.  If you need to use command because

unarchive is insufficient you can add 'warn: false' to this command task or set 'command_warnings=False' in

ansible.cfg to get rid of this message.

changed: [host2]

TASK [install Nginx] ***********************************************************************************************

changed: [host2]

TASK [install : Copy Nginx Start Script] ***************************************************************************

ok: [host2]

TASK [install : Copy Nginx Config] *********************************************************************************

ok: [host2]

TASK [install : create nginx user] *********************************************************************************

ok: [host2]

TASK [install : start nginx service] *******************************************************************************

changed: [host2]

TASK [install : add boot start nginx service] **********************************************************************

changed: [host2]

TASK [install : delete nginx compression files] ********************************************************************

[WARNING]: Consider using the file module with state=absent rather than running 'rm'.  If you need to use command

because file is insufficient you can add 'warn: false' to this command task or set 'command_warnings=False' in

ansible.cfg to get rid of this message.

changed: [host2]

PLAY RECAP *********************************************************************************************************

host2                      : ok=11   changed=5    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

 2.管理配置文件

生产环境中大多数时候需要管理配置文件的,安装软件包只是在初始化环境的时候用一下。下面给写一个管理nginx配置文件的playbook。

(1)实现

创建目录结构

[root@server ~]# mkdir  -p /etc/ansible/nginx_config/roles/{new,old}/{files,handlers,vars,tasks}

[root@server ~]# tree /etc/ansible/nginx_config/

/etc/ansible/nginx_config/

└── roles

    ├── new

    │   ├── files

    │   ├── handlers

    │   ├── tasks

    │   └── vars

    └── old

        ├── files

        ├── handlers

        ├── tasks

        └── vars

11 directories, 0 files

其中new为更新时用到的,old为回滚时用到的,files下面为nginx.conf和vhosts目录,handlers为重启nginx服务的命令

关于回滚,需要在执行playbook之前先备份一下旧的配置,所以对于老配置文件的管理一定要严格,千万不能随便去修改线上机器的配置,并且要保证new/files下面的配置和线上的配置一致。

[root@server ~]#  cd /usr/local/nginx/conf/

[root@server conf]# ls

fastcgi.conf          fastcgi_params.default  mime.types          nginx.conf.default   uwsgi_params

fastcgi.conf.default  koi-utf                 mime.types.default  scgi_params          uwsgi_params.default

fastcgi_params        koi-win                 nginx.conf          scgi_params.default  win-utf

[root@server conf]# cp nginx.conf ./vhosts

[root@server conf]# cp -r nginx.conf vhosts /etc/ansible/nginx_config/roles/new/files/

定义变量

[root@server conf]# cat /etc/ansible/nginx_config/roles/new/vars/main.yml

nginx_basedir: /usr/local/nginx

定义重新加载nginx服务

[root@server conf]# cat /etc/ansible/nginx_config/roles/new/handlers/main.yml

- name: restart nginx

  shell: service nginx restart

核心任务

[root@server conf]# cat /etc/ansible/nginx_config/roles/new/tasks/main.yml

- name: copy conf file

  copy: src={{ item.src }} dest={{ nginx_basedir }}/{{ item.dest }} backup=yes owner=root group=root mode=0644

  with_items:

    - { src: nginx.conf, dest: conf/nginx.conf }

    - { src: vhosts, dest: conf/ }

  notify: restart nginx

定义总入口配置

[root@server conf]# cat /etc/ansible/nginx_config/update.yml

---

- hosts: nginx

  user: root

  roles:

  - new

执行

[root@server conf]# cat /etc/ansible/nginx_config/update.yml

---

- hosts: nginx

  user: root

  roles:

  - new

[root@server conf]# ansible-playbook /etc/ansible/nginx_config/update.yml

[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details

PLAY [nginx] *******************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************

ok: [host2]

TASK [new : copy conf file] ****************************************************************************************

changed: [host2] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})

changed: [host2] => (item={u'dest': u'conf/', u'src': u'vhosts'})

RUNNING HANDLER [new : restart nginx] ******************************************************************************

[WARNING]: Consider using the service module rather than running 'service'.  If you need to use command because

service is insufficient you can add 'warn: false' to this command task or set 'command_warnings=False' in

ansible.cfg to get rid of this message.

changed: [host2]

PLAY RECAP *********************************************************************************************************

host2                      : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

 

(2)验证结果

将80端口改为19端口执行剧本查看端口。

 [root@server conf]# cd /etc/ansible/nginx_config/roles/new/files/

[root@server files]# vi nginx.conf

[root@server files]# vi nginx.conf

[root@server files]# ansible-playbook /etc/ansible/nginx_config/update.yml

[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details

PLAY [nginx] *******************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************

ok: [host2]

TASK [new : copy conf file] ****************************************************************************************

changed: [host2] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})

ok: [host2] => (item={u'dest': u'conf/', u'src': u'vhosts'})

RUNNING HANDLER [new : restart nginx] ******************************************************************************

[WARNING]: Consider using the service module rather than running 'service'.  If you need to use command because

service is insufficient you can add 'warn: false' to this command task or set 'command_warnings=False' in

ansible.cfg to get rid of this message.

changed: [host2]

PLAY RECAP *********************************************************************************************************

host2                      : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

[root@server files]# ansible all-server -m shell -a "ss -tunlp | grep nginx"

[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details

[WARNING]: Could not match supplied host pattern, ignoring: all-server

[WARNING]: No hosts matched, nothing to do

[root@server files]# ansible nginx -m shell -a "ss -tunlp | grep nginx"

[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details

host2 | CHANGED | rc=0 >>

tcp    LISTEN     0      128       *:19                    *:*                   users:(("nginx",pid=6250,fd=6),("nginx",pid=6249,fd=6),("nginx",pid=6247,fd=6))

(3)回滚

回滚的backup.yml对应的roles为old

[root@server files]# rsync -av  /etc/ansible/nginx_config/roles/new/ /etc/ansible/nginx_config/roles/old/

sending incremental file list

files/

files/nginx.conf

files/vhosts

handlers/

handlers/main.yml

tasks/

tasks/main.yml

vars/

vars/main.yml

sent 4,706 bytes  received 127 bytes  9,666.00 bytes/sec

total size is 4,183  speedup is 0.87

回滚操作就是把旧的配置覆盖,然后重新加载nginx服务,每次改动nginx配置文件之前先备份到old里,对应目录为/etc/ansible/nginx_config/roles/old/files

定义总入口配置

 [root@server files]# cat /etc/ansible/nginx_config/rollback.yml

---

- hosts: nginx

  user: root

  roles:

  - old

(4)验证结果

把配置文件的端口改为80端口之后执行new剧本查看端口。

[root@server files]# vi nginx.conf

[root@server files]# ansible-playbook /etc/ansible/nginx_config/update.yml

[root@server files]# ansible nginx -m shell -a "ss -tunlp | grep nginx"

在执行old剧本文件在查看端口

[root@server files]# ansible-playbook /etc/ansible/nginx_config/rollback.yml

[root@server files]# ansible nginx -m shell -a "ss -tunlp | grep nginx"

看到这了给个一键三连呗谢谢各位看官,可以一起交流学习

相关文章
ansible自动化运维(一)简介及清单,模块-CSDN博客
ansible自动化运维(二)playbook模式详解-CSDN博客
ansible自动化运维(三)jinja2模板&&roles角色管理-CSDN博客

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词