接到一个新任务,要求自动给三千台服务器修改账号和密码(统一管控服务器预定用户的使用时间),对这方面比较陌生,就去买了一本python自动化运维(刘天斯著),观摩了大佬的作品,感觉用ansible的api实现这个功能应该是一个不错的思路,只需要在主机上面部署好服务就行,被控服务器不需要部署客户端,默认通过paramiko进行ssh连接下发执行命令或者配置,定时修改账号密码任务的创建是由Flask-APScheduler库触发的,定时任务存储在MySQL里,框架会定期轮询任务,到了预定时间就会触发执行ansible方法。
部署ansible主机服务参考:https://mp.youkuaiyun.com/console/editor/html/109224132
部署ansible的时候有遇到一个坑,在centos7.6下,通过yum安装的ansible,最新版是2.9.14,执行的时候会在baseurl参数那里报错,导致定时任务失败。
查看yum源的ansible版本:
[root@pa_cicd ~]# yum list | grep ansible
ansible.noarch 2.9.14-1.el7 @epel
ansible.noarch 2.9.15-1.el7 epel
ansible-doc.noarch 2.9.15-1.el7 epel
后来通过系统里的python36,安装了新版2.10.3的ansible,步骤如下:
[root@pa_cicd ~]# pip3 install ansible
安装好之后查看版本
[root@pa_cicd ~]# ansible --version
ansible 2.10.3
config file = /etc/ansible/ansible.cfg
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.6/site-packages/ansible
executable location = /usr/local/bin/ansible
python version = 3.6.8 (default, Aug 7 2019, 17:28:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)]
这个版本实测OK,可以完美运行ansible定时任务。
具体项目的目录结构如下:
在main.py模块内,创建APScheduler的实例并启动。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : ********
# @Author : ********
# @function: Flask main model
from flask import Flask, url_for
from flask_apscheduler import APScheduler
from src.database import init_db
f