//Jinja2 变量 Jinja2包含变量和表达式: 变量用"{{}}"包围,表达式用"{%%}"包围 * 字符串类型: {% set var = 'good' %} {{var}} * 列表类型: {% list = [1,2,3] %} {{list[0]}} * 字典类型: {% dict = {'a':1,'b':2} %} {{dict['a']}}
例如: [root@saltserver ~]# vim /srv/salt/var.sls {% set var = 'hello world' %} test_var: cmd.run: - name: echo "var is {{var}}" [root@saltserver ~]# salt '*' state.sls var 192.168.13.187: ---------- ID: test_var Function: cmd.run Name: echo "var is hello world" Result: True Comment: Command "echo "var is hello world"" run Started: 11:07:33.190097 Duration: 19.801 ms Changes: ---------- pid: 29983 retcode: 0 stderr: stdout: var is hello world
Summary for 192.168.13.187 ------------ Succeeded: 1 (changed=1) Failed: 0 ------------ Total states run: 1 Total run time: 19.801 ms
//Jinja2 流程控制 * for 例一: {% for user in users %} {{user}} {% endfor %} 例二: {% for key,value in my_dict.iteritems() %} {{key}} {{value}} {% endfor %}
注意: 模板中循环不能有break和continue.但你可以在迭代中过滤序列来跳过项目 {% for user in users if not user.hidden %} {{user.username}} {% endfor %}
* if 例一: {% if users %} {% for user in users %} {{user.username}} {% endfor %} {% endif %}
例二: {% if kenny.sick %} kenny is sick. {% elif kenny.dead %} You killed Kennny! You bastard!!! {% else %} Kenny looks okay --- so far {% endif %}
salt master启动时会监听两个端口,默认是4505和4506 * 4506 salt master Ret接口,支持认证,文件服务,结果收集等 * 4505 salt master pub接口,提供远程执行命令发送功能
salt minion 启动时从配置文件中获取master地址,如果为域名,则进行解析.解析后,会连接master的4506端口(Ret)进行key认证.认证通过,会获取master的publish_port(4505),然后连接publish_port订阅来自master pub接口任务. 当master下发操作指令时,所有的minion都能接收到,然后minion会检查本机是否匹配.如果匹配,则执行.执行完毕后,把结果发送到master的4506(ret)由master进行处理.命令发送通信完全是异步的,并且命令包很小.此外,这些命令包通过maqpack进行序列化后数据会进一步压缩,所以salt网络负载非常低
执行模块的构成结构
1 2 3 4 5 6 7 8 9 10 11 12
例如: test.sleep def sleep(length): """ Instruct the minion to initiate a process that will sleep for a given period of timezone CLI Example: .. code-block::bash salt '*' test.sleep 20 """ time.sleep(int(length)) return True
* 编写模块 [root@saltserver ~]# vim /srv/salt/_modules/hello.py def world(): """ This is my first function. CLI Example: salt '*' hello.world """ return 'Hello, world!'
* 把模块推送到所有minion上 [root@saltserver ~]# salt '*' saltutil.sync_modules 192.168.13.187: - modules.hello
[root@saltserver ~]# salt '*' sys.list_modules|grep hello - hello
* 在所有minion上执行模块 [root@saltserver ~]# salt '*' hello.world 192.168.13.187: Hello, world!
* __salt__函数 [root@saltserver ~]# vim /usr/local/python27/lib/python2.7/site-packages/salt/modules/useradd.py ret = __salt__['cmd.run_all'](cmd, python_shell=False)
综上,我们可以通过"__salt__"调用所有其他执行模块,就像使用salt命令一样简单
* __grains__和__pillar__函数 [root@saltserver ~]# vim /usr/local/python27/lib/python2.7/site-packages/salt/modules/aptpkg.py if __grains__.get('os_family') in ('Kali', 'Debian', 'neon'): if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'): 综上,可以看出__grains__类似于grain模块,可以获取主机的信息并使用 同样,__pillar__类似于pillar模块
* __virtual__函数 __virtual__函数作用很特殊.salt在加载执行模块时,__virtual__函数可以帮助salt完成以下两项工作: 1.帮助salt决定是否要加载这个模块 2.需要时可以重新命名该模块 例如: [root@saltserver ~]# vim /usr/local/python27/lib/python2.7/site-packages/salt/modules/aptpkg.py # Define the module's virtual name __virtualname__ = 'pkg' def __virtual__(): ''' Confirm this module is on a Debian based system ''' if __grains__.get('os_family') in ('Kali', 'Debian', 'neon'): return __virtualname__ elif __grains__.get('os_family', False) == 'Cumulus': return __virtualname__ return (False, 'The pkg module could not be loaded: unsupported OS family')
* 编写模块 [root@saltserver ~]# vim /srv/salt/_modules/prank.py # -*- coding:utf-8 -*- """ The top nth processes which take up CPU and Memory space usage are available through this module,aditionaly;the module can get the system load information. """
# import python libs import os
# import salt libs import salt.utils
def cpu(n): """ Return the top nth processes which take up the cpu usage for this minion CLI Example: salt '*' prank.cpu <n> """ cmd = "ps aux|sort -k3 -nr|head -n%s" % str(n) output = __salt__['cmd.run_stdout'](cmd) res = [] for line in output.splitlines(): res.append(line) return res
def mem(n): """ Return th top nth processes which take up the memory usage for this minion CLI example: salt '*' prink.mem <n> """ cmd = "ps aux|sort -k4 -nr|head -n%s" % str(n) output = __salt__['cmd.run_stdout'](cmd) res = [] for line in output.splitlines(): res.append(line) return res
def load(): """ Return the load averages for this minion CLI Example: salt '*' prink.load """ load_avg = os.getloadavg() return {'1-min': load_avg[0],'5-min':load_avg[1],'15-min':load_avg[2]}
* 同步模块 [root@saltserver ~]# salt '*' saltutil.sync_modules 192.168.13.187: - modules.prank
* 查看模块帮助 [root@saltserver ~]# salt '192.168.13.187' sys.doc prank prank.cpu: Return the top nth processes which take up the cpu usage for this minion CLI Example: salt '*' prank.cpu <n> prank.load: Return the load averages for this minion CLI Example: salt '*' prink.load <n> prank.mem: Return th top nth processes which take up the memory usage for this minion CLI example: salt '*' prink.mem <n>
//salt-master 接受 minion 秘钥认证 [root@saltserver ~]# salt-key -a 192.168.13.187 The following keys are going to be accepted: Unaccepted Keys: 192.168.13.187 Proceed? [n/Y] Y Key for minion 192.168.13.187 accepted.
//salt-master 查找 minion test 函数使用方法 [root@saltserver ~]# salt '192.168.13.187' sys.doc test.echo test.echo: Return a string - used for testing the connection CLI Example: salt '*' test.echo 'foo bar baz quo qux'
//salt-master 执行 minion test 函数 [root@saltserver ~]# salt '192.168.13.187' test.echo 'Hello WOrld!' 192.168.13.187: Hello WOrld!
例如: [root@saltserver ~]# salt --summary '192.168.13.187' cmd.run 'uptime' 192.168.13.187: 14:39:06 up 5:17, 1 user, load average: 2.00, 1.93, 1.30 ------------------------------------------- Summary ------------------------------------------- # of minions targeted: 1 # of minions returned: 1 # of minions that did not return: 0 # of minions with errors: 0 -------------------------------------------
//第二部分,命令行选项 * -v,--verbose 描述命令执行后,会发生什么(命令执行过程) [root@saltserver ~]# salt --verbose '*' cmd.run_all "echo my salt" Executing job with jid 20170804144256968580 ------------------------------------------- 192.168.13.187: ---------- pid: 26067 retcode: 0 stderr: stdout: my salt
* --summary 显示salt命令概要 [root@saltserver ~]# salt --summary '*' cmd.run_all "echo my salt" 192.168.13.187: ---------- pid: 26073 retcode: 0 stderr: stdout: my salt ------------------------------------------- Summary ------------------------------------------- # of minions targeted: 1 # of minions returned: 1 # of minions that did not return: 0 # of minions with errors: 0 -------------------------------------------
* --out 控制salt执行后的输出格式 [root@saltserver ~]# salt --out=json '*' cmd.run_all "echo my salt" { "192.168.13.187": { "pid": 26079, "retcode": 0, "stderr": "", "stdout": "my salt" } } [root@saltserver ~]# salt --out=yaml '*' cmd.run_all "echo my salt" 192.168.13.187: pid: 26085 retcode: 0 stderr: '' stdout: my salt [root@saltserver ~]# salt --out=raw '*' cmd.run_all "echo my salt" {'192.168.13.187': {'pid': 26091, 'retcode': 0, 'stderr': '', 'stdout': 'my salt'}}
//查看单个数据命令 [root@saltserver ~]# salt '192.168.13.187' pillar.item role
//pillar定位主机 [root@saltserver ~]# salt -I 'role:web' test.ping
* 复合匹配 G G@os:CentOS E E@web\d+\(dev|qa|prod)\.loc P P@os:(redhat|centos|fedora) L L@minion1,minion2,minion3 I I@pdata:foobar S S@192.168.1.0/24 or S@192.168.1.100 R R@%foo.bar
例如: salt -C 'minion-* and G@os:CentOS not E@.*-two$' test.ping
所有的远程执行命令格式都是"<module>.<function>"格式,例如: [root@saltserver ~]# salt '192.168.13.187' sys.list_modules [root@saltserver ~]# salt '192.168.13.187' sys.list_functions test [root@saltserver ~]# salt '192.168.13.187' sys.doc test.sleep
* 创建用户 [wisdom@rabbitmq188 ~]$ /mnt/app/rabbitmq/sbin/rabbitmqctl add_user test test123 Creating user "test" [wisdom@rabbitmq188 ~]$ /mnt/app/rabbitmq/sbin/rabbitmqctl list_users|grep test test []
* 为用户设置角色 [wisdom@rabbitmq188 ~]$ /mnt/app/rabbitmq/sbin/rabbitmqctl set_user_tags test administrator monitoring Setting tags for user "test" to [administrator,monitoring] [wisdom@rabbitmq188 ~]$ /mnt/app/rabbitmq/sbin/rabbitmqctl list_users|grep testtest [administrator, monitoring]
* 为用户设置权限 [wisdom@rabbitmq188 ~]$ /mnt/app/rabbitmq/sbin/rabbitmqctl set_permissions -p /testtest'.*''.*''.*' Setting permissions for user "test"in vhost "/test" [wisdom@rabbitmq188 ~]$ /mnt/app/rabbitmq/sbin/rabbitmqctl list_permissions -p /test Listing permissions in vhost "/test" test .* .* .*
center = Center() #发起5次计算请求 nums= [10, 20, 30, 40 ,50] threads = [] for num in nums: threads.append(MyThread(center.request, num)) for thread in threads: thread.start() for thread in threads: thread.join() EOF