Saltstack study 5: the usage of return and return in the database is too much information on the internet. using return to save the result to the database online, there are already:
1. create a database on the 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;
Create a database user and authorize it to the minion end:
Grant all privileges on salt. * to 'Salt' @ '% 'identified by 'Salt ';
(The account password should be more complex in the actual environment)
2. on the master side, create a custom return script in the/srv/salt/_ returners directory.
[root@test81 _returners]# cat mysql_return.pyfrom contextlib import contextmanagerimport sysimport jsonimport loggingtry:import MySQLdbHAS_MYSQL = Trueexcept ImportError:HAS_MYSQL = Falselog = logging.getLogger(__name__)def __virtual__():if not HAS_MYSQL:return Falsereturn '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] = _attrreturn _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 cursorexcept MySQLdb.DatabaseError as err:error, = err.argssys.stderr.write(error.message)cursor.execute("ROLLBACK")raise errelse: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)))
Note that do not use mysql for the created return name, which may conflict with the built-in mysql return. as to why not use the built-in return, I cannot find the location where to configure the mysql account password.
Here, the minion end needs to use the python module MySQLdb, so you should install this module first:
/Srv/salt/packages/install. sls (the directory and file name are all random)
python26-mysqldb:pkg.installed
salt '*' state.sls packages.install
Finally, we pushed our custom return module:
salt '*' saltutil.sync_returners
Finally, test:
salt '*' cmd.run 'df' --return test_mysql
Then we can see the results in the database: