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

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介:

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,如需转载请自行联系原作者

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助     相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
1月前
|
关系型数据库 API 数据库
盘点Flask与数据库的交互插件——Flask-Sqlalchemy
盘点Flask与数据库的交互插件——Flask-Sqlalchemy
27 0
|
4月前
|
关系型数据库 数据库 PostgreSQL
Docker【应用 03】给Docker部署的PostgreSQL数据库安装PostGIS插件(安装流程及问题说明)
Docker【应用 03】给Docker部署的PostgreSQL数据库安装PostGIS插件(安装流程及问题说明)
154 0
|
4月前
|
SQL 监控 关系型数据库
postgresql|数据库|插件学习(二)---postgresql-12的外置插件pg_profile的启用和使用
postgresql|数据库|插件学习(二)---postgresql-12的外置插件pg_profile的启用和使用
69 0
|
4月前
|
SQL 监控 关系型数据库
postgresql|数据库|插件学习(一)---postgresql-12的内置插件pg_stat_statements的启用和使用
postgresql|数据库|插件学习(一)---postgresql-12的内置插件pg_stat_statements的启用和使用
84 0
|
5月前
|
Java 数据库 数据安全/隐私保护
idea 连接数据库 以及插件mybatisX 生成 entity、mapper、service
idea 连接数据库 以及插件mybatisX 生成 entity、mapper、service
80 0
|
6月前
|
SQL 数据库
IntelliJ IDEA 查看数据库插件(很强大的一个插件)
IntelliJ IDEA 查看数据库插件(很强大的一个插件)
179 0
|
8月前
|
SQL 运维 监控
【运维知识进阶篇】Zabbix5.0稳定版详解11(在Grafana中使用Zabbix插件:安装Grafana+安装Zabbix插件+添加数据源+Grafana直连MySQL数据库取值)(下)
【运维知识进阶篇】Zabbix5.0稳定版详解11(在Grafana中使用Zabbix插件:安装Grafana+安装Zabbix插件+添加数据源+Grafana直连MySQL数据库取值)(下)
118 1
|
7天前
|
关系型数据库 MySQL 分布式数据库
《MySQL 简易速速上手小册》第6章:MySQL 复制和分布式数据库(2024 最新版)
《MySQL 简易速速上手小册》第6章:MySQL 复制和分布式数据库(2024 最新版)
41 2
|
23天前
|
SQL 数据可视化 关系型数据库
轻松入门MySQL:深入探究MySQL的ER模型,数据库设计的利器与挑战(22)
轻松入门MySQL:深入探究MySQL的ER模型,数据库设计的利器与挑战(22)
105 0
|
23天前
|
存储 关系型数据库 MySQL
轻松入门MySQL:数据库设计之范式规范,优化企业管理系统效率(21)
轻松入门MySQL:数据库设计之范式规范,优化企业管理系统效率(21)

热门文章

最新文章