• saltstack主机管理项目:编写插件基类-获取主机列表-提取yaml配置文件(四)


    一、编写插件基类

    1、目录结构

    1、我是如何获知我有多少种系统?

    1. 当客户端第一连接过来的时候,我就已经把这些文件存下来了 ,存在到哪里了?存到数据库了
    2. 每次对主机发送命令的动作时,我从库里把数据取出来,我去判断有几种就可以,每个模块执行之前都要这样的判断,
    3. 直接把用户分配给了不同的模块,这就变成我了我每个模块都要写一边(重复劳动)
    4. 写一个公共的类,就是提取这些,你一定要有一个公共的类,他的作用是为了规范其他的模块

    2、运行结果截图

    cmd和state只要一执行就会自动去提取主机

    二、获取主机列表

    1、目录结构

    2、代码解析

    1、注册admin组件

    from django.contrib import admin
    
    # Register your models here.
    from Arya import models
    admin.site.register(models.Host)
    admin.site.register(models.HostGroup)
    

    2、创建超级用户进入后台创建测试数据

    python manage.py createsuperuser

    3、默认操作系统类型

    from django.db import models
    
    # Create your models here.
    
    class Host(models.Model):
        hostname = models.CharField(max_length=128,unique=True)
        key = models.TextField()
        status_choices = ((0,'Waiting Approval'),
                          (1,'Accepted'),
                          (2,'Rejected'))
    
    
        os_type_choices =(
            ('redhat','RedhatCentOS'),
            ('ubuntu','Ubuntu'),
            ('suse','Suse'),
            ('windows','Windows'),
        )

    4、判断输入的命令有没有超过边界

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author:luoahong
    
    
    class BaseSaltModule(object):
        def __init__(self,sys_argvs,db_models,settings):
            self.db_models = db_models
            self.settings = settings
            self.sys_argvs = sys_argvs
    
        def get_selected_os_types(self):
            data = {}
            for host in self.host_list:
                data[host.os_type] = []
            print('--->data',data)
            return data
        def process(self):
            self.fetch_hosts()
            self.config_data_dic = self.get_selected_os_types()
        def require(self,*args,**kwargs):
            pass
        def fetch_hosts(self):
            print('--fetching hosts---')
    
            if '-h' in self.sys_argvs or '-g' in self.sys_argvs:
                host_list = []
                if '-h' in self.sys_argvs:
                    host_str_index = self.sys_argvs.index('-h') +1
                    if len(self.sys_argvs) <= host_str_index:
                        exit("host argument must be provided after -h")
                    else: #get the host str
                        host_str = self.sys_argvs[host_str_index]
                        host_str_list = host_str.split(',')
                        host_list += self.db_models.Host.objects.filter(hostname__in=host_str_list)
                if '-g' in self.sys_argvs:
                    group_str_index = self.sys_argvs.index('-g') +1
                    if len(self.sys_argvs) <= group_str_index:
                        exit("group argument must be provided after -g")
                    else: #get the group str
                        group_str = self.sys_argvs[group_str_index]
                        group_str_list = group_str.split(',')
                        group_list = self.db_models.HostGroup.objects.filter(name__in=group_str_list)
                        for group in group_list:
                            host_list += group.hosts.select_related()
                self.host_list = set(host_list)
                return True
                print('----host list:', host_list)
            else:
                exit("host [-h] or group[-g] argument must be provided")
    
    
        def syntax_parser(self,section_name,mod_name,mod_data):
            print("-going to parser state data:",section_name,mod_name)
            for state_item in mod_data:
                print("	",state_item)
                for key,val in state_item.items():
                    if hasattr(self,key):
                        state_func = getattr(self,key)
                        state_func(val)
                    else:
                        exit("Error:module [%s] has no argument [%s]" %( mod_name,key ))

    三、提取yaml配置文件

    1、提取配置文件模板

    apache:
      pkg.installed: []
       service.running:
         - reload: True
         - watch:
           - file: /etc/httpd/conf/httpd.conf
      user.present:
        - uid: 87
        #- username: alex
        - gid: 87
        - home: /var/www/html
        - shell: /bin/nologin
        - require:
          - group: apache
      group.present:
        - gid: 87
        - require:
          - pkg: apache
    
     /etc/httpd/conf/httpd.conf:
       file.managed:
         - source: salt://apache/httpd.conf
         - user: root
         - group: root
         - mode: 644

    2、目录结构

    4、提取配置文件python文件

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author:luoahong
    
    
    class BaseSaltModule(object):
        def __init__(self,sys_argvs,db_models,settings):
            self.db_models = db_models
            self.settings = settings
            self.sys_argvs = sys_argvs
    
        def get_selected_os_types(self):
            data = {}
            for host in self.host_list:
                data[host.os_type] = []
            print('--->data',data)
            return data
        def process(self):
            self.fetch_hosts()
            self.config_data_dic = self.get_selected_os_types()
        def require(self,*args,**kwargs):
            pass
        def fetch_hosts(self):
            print('--fetching hosts---')
    
            if '-h' in self.sys_argvs or '-g' in self.sys_argvs:
                host_list = []
                if '-h' in self.sys_argvs:
                    host_str_index = self.sys_argvs.index('-h') +1
                    if len(self.sys_argvs) <= host_str_index:
                        exit("host argument must be provided after -h")
                    else: #get the host str
                        host_str = self.sys_argvs[host_str_index]
                        host_str_list = host_str.split(',')
                        host_list += self.db_models.Host.objects.filter(hostname__in=host_str_list)
                if '-g' in self.sys_argvs:
                    group_str_index = self.sys_argvs.index('-g') +1
                    if len(self.sys_argvs) <= group_str_index:
                        exit("group argument must be provided after -g")
                    else: #get the group str
                        group_str = self.sys_argvs[group_str_index]
                        group_str_list = group_str.split(',')
                        group_list = self.db_models.HostGroup.objects.filter(name__in=group_str_list)
                        for group in group_list:
                            host_list += group.hosts.select_related()
                self.host_list = set(host_list)
                return True
                print('----host list:', host_list)
            else:
                exit("host [-h] or group[-g] argument must be provided")
    
    
        def syntax_parser(self,section_name,mod_name,mod_data):
            print("-going to parser state data:",section_name,mod_name)
            for state_item in mod_data:
                print("	",state_item)
                for key,val in state_item.items():
                    if hasattr(self,key):
                        state_func = getattr(self,key)
                        state_func(val)
                    else:
                        exit("Error:module [%s] has no argument [%s]" %( mod_name,key ))

    5、运行截图

    1、获主机信息

    2、打印模块详细信息

    打印结果截图

  • 相关阅读:
    show processlist 输出ID 和 information_schema.PROCESSLIST 的id,information_schema.innodb_trx的TRX_MYSQL_T
    用 Flask 来写个轻博客 (15) — M(V)C_实现博文页面评论表单
    第十二章 对象(下)
    十大最值得关注的国内大数据分析厂商
    第十二章 对象(上)
    mysql 区间锁 对于没有索引 非唯一索引 唯一索引 各种情况
    insert into select 堵塞update
    监控持有sql和被堵塞的sql
    人生应该有间隔年——北漂18年(75)
    ERROR: transport error 202: connect failed: Connection timed out
  • 原文地址:https://www.cnblogs.com/luoahong/p/9426736.html
Copyright © 2020-2023  润新知