fdgsdf 发表于 2015-8-11 08:39:41

自动化运维工具Ansible之Python API

Ansible 的Python API使用起来相当简单快捷,使用API可以将某些运维操作封装成一个带有WEB界面的操作,免去了每次执行某个操作的时候都需要SSH运行Ansible命令。
官方给出的一个简单示例:

1
2
3
4
5
6
7
8
9
import ansible.runner
   
    runner = ansible.runner.Runner(
       module_name='ping',
       module_args='',
       pattern='web*',
       forks=10
    )
    datastructure = runner.run()




run()方法会返回执行的结果。返回的数据是一个JSON格式的:

1
2
3
4
5
6
7
8
    {
      "dark" : {
         "web1.example.com" : "failure message"
      },
      "contacted" : {
         "web2.example.com" : 1
      }
    }




Ansible的API使用起来就这么方便,先是导入ansible,然后直接调用相应的模块,赋值相应的模块参数即可。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    # cat an.py
    #!/usr/bin/env python
   
    import ansible.runner
   
    runner = ansible.runner.Runner(
      module_name='ping',#调用的模块
      module_args='',#模块参数
      pattern='webservers',#主机组,可以是正则表达式如web*
      forks=10
    )
   
    data = runner.run()
    print data
    # python an.py
    {'dark': {}, 'contacted': {'192.168.1.65': {'invocation': {'module_name': 'ping', 'module_args': ''}, u'changed': False, u'ping': u'pong'}}}




默认使用的主机资源文件位置为/etc/ansible/hosts,也可以指定host_list参数,来指定一个inventory文件的路径,也可以指定一个动态的inventory脚本。dark里面是执行失败的主机列表,contacted是执行操作成功的主机列表。

但是并不是所有的模块都可以通过API调用的,如template模块,在ansible1.9或之前的版本中,就无法通过Python API调用。
页: [1]
查看完整版本: 自动化运维工具Ansible之Python API