Ansible 2.0 最新版本的API封装

ansible 2.0之后的api变更了, 下面是封装好了2.0之后的api使用方法

具体的使用, 方法内有案例. 如果看过ansible的源码, 就可以容易理解这个API的封装. 其中要说的是 self.options 这个. 这个是构建命令行参数的, 当我们使用命令行上去执行指令ansible -i /etc/ansible/hosts localhost -m ping 时, 虽然只带了-i 和 -m 指定模块, 但是有很多默认值. 最终的所有参数的设置, 都是附加到self.options的

想去了解ansible API的同学, 建议去 自己分析下源码 /usr/lib/python2.6/site-packages/ansible/cli/adhoc.py; 就很容易明白了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Ycan
# More: http://www.ehco.me/
# Ansible API
# Ansible Version >=2.0
from __future__ import (absolute_import, division, print_function)
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.inventory import Inventory
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from collections import namedtuple
from ansible.playbook.play import Play
from ansible import constants as C
from ansible.parsing.splitter import parse_kv
from ansible.executor.playbook_executor import PlaybookExecutor
from ansible.utils.vars import load_extra_vars
import os
class DoGoAnsibleEorror(Exception): pass
class DoGoMinix(object):
""" 列出一些基础的options
subset: '127.0.0.1'
extra_vars: ["name='yagcan'"] 或者 json格式也可以
tags: "test,test01"
"""
def __init__(self, inventory_file=None, passwords=None, verbosity=0, cb='minimal'):
if passwords is None:
passwords = {'conn_pass': '', 'become_pass': ''}
if inventory_file is None:
inventory_file = C.DEFAULT_HOST_LIST
self.verbosity = verbosity
self.inventory_file = inventory_file
self.passwords = passwords
self.cb = cb
self._set_option = False
self._set_hosts = False
# initialize needed objects
self.variable_manager = VariableManager()
self.loader = DataLoader()
def _base_option(self):
""" base option"""
return dict(
connection=C.DEFAULT_TRANSPORT,
forks=C.DEFAULT_FORKS,
become=False,
become_method=C.DEFAULT_BECOME_METHOD,
become_user=None,
check=False,
module_path=None,
remote_user=C.DEFAULT_REMOTE_USER,
private_key_file=C.DEFAULT_PRIVATE_KEY_FILE,
ssh_common_args='',
sftp_extra_args='',
scp_extra_args='',
ssh_extra_args='',
verbosity=self.verbosity,
listhosts=False,
listtags=False,
listtasks=False,
syntax=False,
inventory=None
)
def limit_hosts(self, host_lists):
# --limit
self._set_hosts = True
self.host_lists = host_lists
if isinstance(host_lists, list):
self.host_lists = ','.join(host_lists)
def set_option(self, **kwargs):
""" set Options
usage:
base_option = self._base_option()
_option = base_option.copy()
_option.upadte({'verbosity': 1, 'forks': 20})
self.set_option(**_option)
"""
self._set_option = True
self.options = self._options(**kwargs)
def _options(self, **kwargs):
""" set options
"""
keys = kwargs.keys()
Options = namedtuple('Options', keys)
v = Options(**kwargs)
if v.inventory is not None:
self.inventory_file = v.inventory
return v
def _prepare_run(self):
# initialize needed objects
# when not set_option
if self._set_option is False:
_base_option = self._base_option().copy()
self.options = self._options(**_base_option)
self.inventory = Inventory(loader=self.loader, variable_manager=self.variable_manager,
host_list=self.inventory_file)
self.variable_manager.set_inventory(self.inventory)
if self._set_hosts:
self.inventory.subset(self.host_lists)
if len(self.inventory.list_hosts()) == 0:
raise DoGoAnsibleEorror(u'match any hosts empty..')
def run(self, play_data):
pass
class DoGoAdHocCLI(DoGoMinix):
def __init__(self, *args, **kwargs):
""" 案例:
adh = DoGoAdHocCLI(inventory_file='/etc/ansible/hosts')
_base_options = adh._base_option()
options = _base_options.copy()
options.update({
'inventory': '/etc/ansible/hosts',
'forks': 10
})
adh.set_option(**options)
play_data = dict(
name="DoGo CMDB gather facts",
hosts=['localhost'],
gather_facts=True,
tasks=[dict(action=dict(module='setup'))]
)
return adh.run(play_data)
"""
super(DoGoAdHocCLI, self).__init__(*args, **kwargs)
def run(self, play_data):
"""
play_data = dict(
name="Ansible Ad-Hoc",
hosts=pattern,
gather_facts=True,
tasks=[dict(action=dict(module='service', args={'name': 'vsftpd', 'state': 'restarted'}), async=async, poll=poll)]
)
"""
self._prepare_run()
play = Play().load(play_data, variable_manager=self.variable_manager, loader=self.loader)
tqm = None
try:
tqm = TaskQueueManager(
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
passwords=self.passwords,
stdout_callback=self.cb,
run_additional_callbacks=C.DEFAULT_LOAD_CALLBACK_PLUGINS,
run_tree=False,
)
result = tqm.run(play)
return result
finally:
if tqm:
tqm.cleanup()
class DoGoPlaybookCLI(DoGoMinix):
def __init__(self, *args, **kwargs):
""" example:
play_book = get_ansible_task_file('task_rsync.yml')
forks = len(host_list)
if forks == 0:
raise ValueError('host_list empty....')
if forks > 10: forks = 10
pb = DoGoPlaybookCLI(inventory_file='/etc/ansible/hosts', cb='skippy')
_base_options = pb._base_option()
options = _base_options.copy()
options.update({
'inventory': '/etc/ansible/hosts',
'forks': forks,
'tags': 'add_rsync_module',
'subset': ','.join(host_list),
'extra_vars': [json.dumps({'module': module})]
})
pb.set_option(**options)
pb.limit_hosts(','.join(host_list))
if not os.path.isfile(play_book):
raise OSError('task file {0} not found!'.format(play_book))
kw = {'playbooks': [play_book]}
return pb.run(**kw)
"""
super(DoGoPlaybookCLI, self).__init__(*args, **kwargs)
def run(self, playbooks):
"""
param: `playbooks`: type string or list, example: ['/etc/ansible/test.yml'], '/etc/ansible/test1.yml, /etc/ansible/test2.yml'
param: `limit`: eq --limit ''
"""
self._prepare_run()
self.variable_manager.extra_vars = load_extra_vars(loader=self.loader, options=self.options)
results = 0
if isinstance(playbooks, basestring):
if ',' in playbooks:
playbooks = [pl.strip() for pl in playbooks.split(',') if os.path.exists(pl)]
else:
playbooks = [playbooks] if os.path.exists(playbooks) else []
if len(playbooks) == 0:
raise DoGoAnsibleEorror(u'{0} invalid'.format(playbooks))
try:
# create the playbook executor, which manages running the plays via a task queue manager
pbex = PlaybookExecutor(playbooks=playbooks, inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader, options=self.options, passwords=self.passwords)
results = pbex.run()
except Exception, ex:
results = str(ex)
finally:
return results
def test_setup(host_list=[]):
# 测试setup模块
if host_list:
adh = DoGoAdHocCLI(inventory_file='/etc/ansible/hosts')
_base_options = adh._base_option()
options = _base_options.copy()
options.update({
'inventory': '/etc/ansible/hosts'
})
adh.set_option(**options)
play_data = dict(
name="DoGo CMDB gather facts",
hosts=host_list,
gather_facts=True,
tasks=[dict(action=dict(module='setup'))]
)
return adh.run(play_data)
return False
if __name__ == '__main__':
test_setup(host_list=['127.0.0.1'])
分享即快乐,谢谢你请思哲小朋友吃糖!