Heim >Datenbank >MySQL-Tutorial >saltstack学习五:return及入库_MySQL
return的用法网上太多资料了,利用return把结果存入数据库网上已经有现在的:
1、在master端创建数据库:
CREATE DATABASE `salt`DEFAULT CHARACTER SET utf8DEFAULT COLLATE utf8_general_ci;USE `salt`;---- Table structure for table `jids`--DROP TABLE IF EXISTS `jids`;CREATE TABLE `jids` (`jid` varchar(255) NOT NULL,`load` mediumtext NOT NULL,UNIQUE KEY `jid` (`jid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;---- Table structure for table `salt_returns`--DROP TABLE IF EXISTS `salt_returns`;CREATE TABLE `salt_returns` (`fun` varchar(50) NOT NULL,`jid` varchar(255) NOT NULL,`return` mediumtext NOT NULL,`id` varchar(255) NOT NULL,`success` varchar(10) NOT NULL,`full_ret` mediumtext NOT NULL,KEY `id` (`id`),KEY `jid` (`jid`),KEY `fun` (`fun`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
创建数据库用户,并授权给minion端:
GRANT ALL PRIVILEGES ON salt.* to ‘salt’@'%’ identified by ‘salt’;
(在实际环境中帐号密码应该复杂一些)
2、在master端,创建自定义return脚本,路径在/srv/salt/_returners目录下
[root@test81 _returners]# cat mysql_return.pyfrom contextlib import contextmanagerimport sysimport jsonimport loggingtry: import MySQLdb HAS_MYSQL = Trueexcept ImportError: HAS_MYSQL = Falselog = logging.getLogger(__name__)def __virtual__(): if not HAS_MYSQL: return False return 'test_mysql'def _get_options(): ''' Returns options used for the MySQL connection. ''' defaults = {'host': '192.168.2.100', 'user': 'salt', 'pass': 'salt', 'db': 'salt', 'port': 3306} _options = {} for attr in defaults: _attr = __salt__['config.option']('mysql.{0}'.format(attr)) if not _attr: log.debug('Using default for MySQL {0}'.format(attr)) _options[attr] = defaults[attr] continue _options[attr] = _attr return _options@contextmanagerdef _get_serv(commit=False): ''' Return a mysql cursor ''' _options = _get_options() conn = MySQLdb.connect(host=_options['host'], user=_options['user'], passwd=_options['pass'], db=_options['db'], port=_options['port']) cursor = conn.cursor() try: yield cursor except MySQLdb.DatabaseError as err: error, = err.args sys.stderr.write(error.message) cursor.execute("ROLLBACK") raise err else: if commit: cursor.execute("COMMIT") else: cursor.execute("ROLLBACK") finally: conn.close()def returner(ret): ''' Return data to a mysql server ''' with _get_serv(commit=True) as cur: sql = '''INSERT INTO `salt_returns` (`fun`, `jid`, `return`, `id`, `success`, `full_ret` ) VALUES (%s, %s, %s, %s, %s, %s)''' cur.execute(sql, (ret['fun'], ret['jid'], str(ret['return']), ret['id'], ret['success'], json.dumps(ret)))
注意创建的return名字不要用mysql,这样有可能会和自带的mysql return冲突,至于为什么不用自带的return,我实在找不到配置mysql帐号密码在哪里搞
这里minion端需要用到MySQLdb这个python模块,所以应该先安装这个模块:
/srv/salt/packages/install.sls (目录和文件名都是随便起的)
python26-mysqldb:pkg.installed
salt '*' state.sls packages.install
最后推送刚刚我们自定义的return模块:
salt '*' saltutil.sync_returners
最后测试一下:
salt '*' cmd.run 'df' --return test_mysql
然后可以看到数据库里面有结果: