- Extending SaltStack
- Joseph Hall
- 239字
- 2021-07-16 12:42:18
The final module
When we put all of the preceding code together, we end up with the following module:
''' This module should be saved as salt/modules/mysqltest.py ''' import salt.utils try: import MySQLdb HAS_LIBS = True except ImportError: HAS_LIBS = False import logging log = logging.getLogger(__name__) __func_alias__ = { 'list_': 'list' } __virtualname__ = 'mysqltest' def __virtual__(): ''' Check dependencies, using both methods from the chapter ''' if not salt.utils.which('mysql'): return False if HAS_LIBS: return __virtualname__ return False def ping(): ''' Returns True CLI Example: salt '*' mysqltest.ping ''' return True def check_mysqld(): ''' Check to see if sshd is running and listening CLI Example: salt '*' testmodule.check_mysqld ''' output = __salt__['cmd.run']('netstat -tulpn | grep mysqld', python_shell=True) if 'tcp' not in output: return False return True def _get_conn(): ''' Get a database connection object ''' user = __salt__['config.get']('mysql_user', 'root') passwd = __salt__['config.get']('mysql_pass', '') host = __salt__['config.get']('mysql_host', 'localhost') port = __salt__['config.get']('mysql_port', 3306) db_ = __salt__['config.get']('mysql_db', 'mysql') dbc = MySQLdb.connect( connection_user=user, connection_pass=passwd, connection_host=host, connection_port=port, connection_db=db_, ) log.trace('Connected to the database') return dbc def version(): ''' Returns MySQL Version CLI Example: salt '*' mysqltest.version ''' dbc = _get_conn() cur = dbc.cursor() return cur.execute('SELECT VERSION()') def list_(type_): ''' List different resources in MySQL CLI Examples: salt '*' mysqltest.list tables salt '*' mysqltest.list databases ''' dbc = _get_conn() cur = dbc.cursor() valid_types = ['tables', 'databases'] if type_ not in valid_types: err_msg = 'A valid type was not specified' log.error(err_msg) raise CommandExecutionError(err_msg) return cur.execute('SHOW {0}()'.format(type_))
推薦閱讀
- Mastering Mesos
- 面向STEM的mBlock智能機器人創新課程
- Blockchain Quick Start Guide
- PyTorch深度學習實戰
- 21天學通ASP.NET
- AutoCAD 2012中文版繪圖設計高手速成
- 大學C/C++語言程序設計基礎
- Windows Server 2008 R2活動目錄內幕
- Dreamweaver CS6中文版多功能教材
- 網絡管理工具實用詳解
- 嵌入式GUI開發設計
- C#編程兵書
- Moodle 2.0 Course Conversion(Second Edition)
- Learning iOS 8 for Enterprise
- Getting Started with Tableau 2019.2