3.ansible1.7.2 callback插件获取硬件信息并插入到数据库中

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS PostgreSQL,集群系列 2核4GB
简介:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#url: http://www.shencan.net/index.php/2014/07/17/ansible-%E6%8F%92%E4%BB%B6%E4%B9%8Bcallback_plugins-%EF%BC%88%E5%AE%9E%E6%88%98%EF%BC%89/
 
cat  / etc / ansible / ansible.cfg|grep callback|grep  - "#"
callback_plugins    =  / usr / share / ansible / plugins / callback
bin_ansible_callbacks  =  True
 
 
cat  / usr / share / ansible / plugins / callback / log_plays.py
#!/usr/bin/env python
# coding:utf8
# 插入到数据库中
import  simplejson
import  sys
import  commands
import  MySQLdb
import  os
import  json
import  time
# import sqlite3
#import redis
import  datetime
from  pymongo  import  MongoClient
 
 
mongoinfo  =  { "host" : "127.0.0.1" , "port" : "27408" , "user" : "root" , "password" : "root" , "dbname" : "ansible_log" }  
 
 
dbname  =  '/tmp/setup.db'
TIME_FORMAT = '%Y-%m-%d %H:%M:%S'
 
'''
try:
     con = sqlite3.connect(dbname)
     cur = con.cursor()
except:
     pass
'''
 
def  InsertMDB(values):
     global  mongoinfo
     dbhost  =  mongoinfo[ 'host' ]
     dbport  =  mongoinfo[ 'port' ]
     dbuser  =  mongoinfo[ 'user' ]
     dbpwd   =  mongoinfo[ 'password' ]
     dbname  =  mongoinfo[ 'dbname' ]
     uri  =  'mongodb://%s:%s@%s/%s' % (dbuser,dbpwd,dbhost,dbname)
     #client = MongoClient(uri,safe=False)
     client  =  MongoClient(uri)
     db  =  client.ansible_log
     db.callback.insert(values)
 
class  DB():
     def  __init__( self ):
         self .db  =  MySQLdb.connect( "localhost" "root" "root" "cmdb" )
         self .cursor  =  self .db.cursor()
     def  insert_hosts( self ,ipdict):
             ip  =  ipdict[ 'ip' ]
             hostname  =  ipdict[ 'hostname' ]
             vcpus  =  ipdict[ 'cpu_core' ]
             mem  =  ipdict[ 'memory' ]
             disk_total  =  ipdict[ 'disk' ]
             check_host  =  "select * from hosts_copy where IP = '%s' "  %  (ip)
             flag  =  self .cursor.execute(check_host)
             if  flag ! =  0L :
                 sql  =  "update hosts_copy set hostname = '%s',vcpus = '%s',mem = '%s',disk_total ='%s' where ip = '%s' "  %  (
                     hostname, vcpus, mem, disk_total, ip)
                 try :
                     print  (sql,  '******************' )
                     self .cursor.execute(sql)
                     # 提交到数据库执行
                     self .db.commit()
                     print  ( " '%s' update successfully !" %  (ip)
                 except :
                     # 发生错误时回滚
                     self .db.rollback()
                     print  'Something is wrong !!! '
             else :
                 sql  =  "INSERT INTO hosts_copy(ip,hostname,vcpus,mem,disk_total) VALUES('%s','%s','%s','%s','%s')"  %  (
                     ip, hostname, vcpus, mem, disk_total)
                 print  sql
                 self .cursor.execute(sql)
                 self .db.commit()
 
 
 
 
 
def  log(host, data):
     pass
#    if type(data) == dict:
#        invocation = data.pop('invocation', None)
#        if invocation.get('module_name', None) != 'setup':
#            return
#
#    facts = data.get('ansible_facts', None)
#
#    now = time.strftime(TIME_FORMAT, time.localtime())
#
#    try:
#        # `host` is a unique index
#        cur.execute("REPLACE INTO inventory (now, host, arch, dist, distvers, sys,kernel) VALUES(?,?,?,?,?,?,?);",
#        (
#            now,
#            facts.get('ansible_hostname', None),
#            facts.get('ansible_architecture', None),
#            facts.get('ansible_distribution', None),
#            facts.get('ansible_distribution_version', None),
#            facts.get('ansible_system', None),
#            facts.get('ansible_kernel', None)
#        ))
#        con.commit()
#    except:
#        pass
#
class  CallbackModule( object ):
     def  runner_on_ok( self , host, res):
         if  'stdout'  in  res.keys()  and  res[ 'stdout' ]:
             #print eval(res['stdout'].encode("utf-8"))
             #res_stdout = res['stdout'].encode("utf-8")
             res_stdout  =  res[ 'stdout' ].strip( '\r\n' ).split( '\n' )[ - 1 ]
             try :
                             res_dict  =  eval (res_stdout)
                             db  =  DB()
                             db.insert_hosts(res_dict)
                         except :
                             pass
             
         #host=host=res._host.get_name()
         #r = redis.Redis(host='127.0.0.1', port=6379, db=0) 
         #r.set(host,str(res))
         #f = open('/tmp/11','a')
         #f.write(str(host))
         #f.write(str(res))
         #f.close()
         #log(host, res)
         '''
         now = datetime.datetime.now()
         result = res
         result['time'] = now.strftime(TIME_FORMAT)
         result['status'] = 'ok'
         InsertMDB(result)
         '''
     def  runner_on_failed( self , host, res, ignore_errors = False ):
         =  open ( '/tmp/12' , 'a' )
         f.write( str (host))
         f.write( str (res))
         f.close()
         log(host, res)
 
 
 
说明
1. 插入mongodb
2. 插入mysql
在插入mysql的时候,最基本的log(host, data),可以获取setup的信息,所以在做机器初始化,可以通过setup模块获取,额外的需要自己写脚本,然后得到res


使用ansible-playbook -i hosts main.yml



最后附一张大神做的图片

QQ20140718-1@2x1.png



本文转自 liqius 51CTO博客,原文链接:http://blog.51cto.com/szgb17/2049678,如需转载请自行联系原作者

相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助     相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
11天前
|
人工智能 JavaScript 关系型数据库
【02】Java+若依+vue.js技术栈实现钱包积分管理系统项目-商业级电玩城积分系统商业项目实战-ui设计图figmaUI设计准备-figma汉化插件-mysql数据库设计-优雅草卓伊凡商业项目实战
【02】Java+若依+vue.js技术栈实现钱包积分管理系统项目-商业级电玩城积分系统商业项目实战-ui设计图figmaUI设计准备-figma汉化插件-mysql数据库设计-优雅草卓伊凡商业项目实战
57 14
【02】Java+若依+vue.js技术栈实现钱包积分管理系统项目-商业级电玩城积分系统商业项目实战-ui设计图figmaUI设计准备-figma汉化插件-mysql数据库设计-优雅草卓伊凡商业项目实战
|
3月前
|
SQL Java 数据库连接
深入 MyBatis-Plus 插件:解锁高级数据库功能
Mybatis-Plus 提供了丰富的插件机制,这些插件可以帮助开发者更方便地扩展 Mybatis 的功能,提升开发效率、优化性能和实现一些常用的功能。
548 26
深入 MyBatis-Plus 插件:解锁高级数据库功能
|
4月前
|
自然语言处理 关系型数据库 MySQL
MySQL数据库使用Match语法需要安装什么插件吗?
【10月更文挑战第1天】MySQL数据库使用Match语法需要安装什么插件吗?
118 0
|
8月前
|
XML 关系型数据库 数据库
使用mybatis-generator插件生成postgresql数据库model、mapper、xml
使用mybatis-generator插件生成postgresql数据库model、mapper、xml
697 0
|
8月前
|
存储 安全 关系型数据库
安全开发-PHP应用&留言板功能&超全局变量&数据库操作&第三方插件引用&后台模块&Session&Cookie&Token&身份验证&唯一性
安全开发-PHP应用&留言板功能&超全局变量&数据库操作&第三方插件引用&后台模块&Session&Cookie&Token&身份验证&唯一性
|
8月前
|
PHP 数据库 数据安全/隐私保护
Duplicator插件如何进行数据库备份?
【6月更文挑战第4天】Duplicator插件如何进行数据库备份?
116 1
|
9月前
|
SQL JSON 关系型数据库
[UE虚幻引擎插件DTPostgreSQL] PostgreSQL Connector 使用蓝图连接操作 PostgreSQL 数据库说明
本插件主要是支持在UE蓝图中连接和操作PostgreSQL 数据库。
85 2
|
3天前
|
关系型数据库 MySQL 网络安全
如何排查和解决PHP连接数据库MYSQL失败写锁的问题
通过本文的介绍,您可以系统地了解如何排查和解决PHP连接MySQL数据库失败及写锁问题。通过检查配置、确保服务启动、调整防火墙设置和用户权限,以及识别和解决长时间运行的事务和死锁问题,可以有效地保障应用的稳定运行。
47 25
|
12天前
|
关系型数据库 MySQL 数据库
Docker Compose V2 安装常用数据库MySQL+Mongo
以上内容涵盖了使用 Docker Compose 安装和管理 MySQL 和 MongoDB 的详细步骤,希望对您有所帮助。
91 42
|
26天前
|
关系型数据库 MySQL 数据库连接
数据库连接工具连接mysql提示:“Host ‘172.23.0.1‘ is not allowed to connect to this MySQL server“
docker-compose部署mysql8服务后,连接时提示不允许连接问题解决

热门文章

最新文章