码迷,mamicode.com
首页 > Windows程序 > 详细

Ansible API和自定义module

时间:2020-05-28 00:50:30      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:ict   from   timer   lap   shu   ssi   collect   sam   could   

技术图片
 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

标签:ict   from   timer   lap   shu   ssi   collect   sam   could   

原文地址:https://www.cnblogs.com/xuqidong/p/12977547.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!