Ansible API和自定义module

Posted xuqidong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ansible API和自定义module相关的知识,希望对你有一定的参考价值。

技术图片
 1 #!/usr/bin/env python
 2 
 3 import json
 4 import shutil
 5 from ansible.module_utils.common.collections import ImmutableDict
 6 from ansible.parsing.dataloader import DataLoader
 7 from ansible.vars.manager import VariableManager
 8 from ansible.inventory.manager import InventoryManager
 9 from ansible.playbook.play import Play
10 from ansible.executor.task_queue_manager import TaskQueueManager
11 from ansible.plugins.callback import CallbackBase
12 from ansible import context
13 import ansible.constants as C
14 
15 class ResultCallback(CallbackBase):
16     """A sample callback plugin used for performing an action as results come in
17 
18     If you want to collect all results into a single object for processing at
19     the end of the execution, look into utilizing the ``json`` callback plugin
20     or writing your own custom callback plugin
21     """
22     def v2_runner_on_ok(self, result, **kwargs):
23         """Print a json representation of the result
24 
25         This method could store the result in an instance attribute for retrieval later
26         """
27         host = result._host
28         print json.dumps({host.name: result._result}, indent=4)
29 
30 # since the API is constructed for CLI it expects certain options to always be set in the context object
31 context.CLIARGS = ImmutableDict(connection=local, module_path=[ping], forks=10, become=None,
32                                 become_method=None, become_user=None, check=False, diff=False)
33 
34 # initialize needed objects
35 loader = DataLoader() # Takes care of finding and reading yaml, json and ini files
36 passwords = dict(vault_pass=secret)
37 
38 # Instantiate our ResultCallback for handling results as they come in. Ansible expects this to be one of its main display outlets
39 results_callback = ResultCallback()
40 
41 # create inventory, use path to host config file as source or hosts in a comma separated string
42 inventory = InventoryManager(loader=loader, sources=/etc/ansible/hosts)
43 
44 # variable manager takes care of merging all the different sources to give you a unified view of variables available in each context
45 variable_manager = VariableManager(loader=loader, inventory=inventory)
46 
47 # create data structure that represents our play, including tasks, this is basically what our YAML loader does internally.
48 play_source =  dict(
49         name = "Ansible Play",
50         hosts = all,
51         gather_facts = no,
52         tasks = [
53             dict(action=dict(module=shell, args=(ls /tmp)), register=shell_out),
54             dict(action=dict(module=debug, args=dict(msg={{shell_out.stdout}})))
55          ]
56     )
57 
58 # Create play object, playbook objects use .load instead of init or new methods,
59 # this will also automatically create the task objects from the info provided in play_source
60 play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
61 
62 # Run it - instantiate task queue manager, which takes care of forking and setting up all objects to iterate over host list and tasks
63 tqm = None
64 try:
65     tqm = TaskQueueManager(
66               inventory=inventory,
67               variable_manager=variable_manager,
68               loader=loader,
69               passwords=passwords,
70               stdout_callback=results_callback,  # Use our custom callback instead of the ``default`` callback plugin, which prints to stdout
71           )
72     result = tqm.run(play) # most interesting data for a play is actually sent to the callback‘s methods
73 finally:
74     # we always need to cleanup child procs and the structures we use to communicate with them
75     if tqm is not None:
76         tqm.cleanup()
77 
78     # Remove ansible tmpdir
79     shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
ansible_api.py
技术图片
 1 #!/usr/bin/python
 2 
 3 import datetime
 4 import sys
 5 import json
 6 import os
 7 import shlex
 8 
 9 
10 args_file = sys.argv[1]
11 args_data = file(args_file).read()
12 
13 arguments = shlex.split(args_data)
14 for arg in arguments:
15     if = in arg:
16         (key, value) = arg.split(=)
17         if key == time:
18             rc = os.system("date -s ‘%s‘" % value)
19             if rc != 0:
20                 print json.dumps({failed: True, msg: failed setting the time})
21                 sys.exit(1)
22             date = str(datetime.datetime.now())
23             print json.dumps({time: date, changed: True})
24             sys.exit(0)
25             
26 date = str(datetime.datetime.now())
27 print json.dumps({time: date})
28                 
timer.py

 

以上是关于Ansible API和自定义module的主要内容,如果未能解决你的问题,请参考以下文章

带有复选框和自定义适配器的 ListView,片段无法正常工作

如何使用Ansible 2的API做python开发

Microsoft Graph 和自定义 API 的访问令牌

XMPP 服务器和自定义 API

扩展 IdentityUser 和自定义查询的 Web API

标记之间的 Google Maps API 和自定义折线路线