使用Ansible Python API,如何在代码中访问任务级输出?

时间:2015-04-28 04:32:28

标签: python python-2.7 ansible ansible-playbook

我使用像这样的剧本跑步者:

stats = callbacks.AggregateStats()                                           
playbook_cb = callbacks.PlaybookCallbacks(verbose=1)           
runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=1)                                 

pb = ansible.playbook.PlayBook(
... # basic info
)                                                                          
results = pb.run()

结果变量包含如下输出:

{"status": 1, "result": {"127.0.0.1": {"unreachable": 0, "skipped": 0, "ok": 3, "changed": 2, "failures": 0}}}

哪个好。但是我还需要像下面显示的dict一样的任务级别输出:

changed: [127.0.0.1] => {"changed": true, "name": "apache2", "state": "started"}

我尝试改变冗长,但这不是我想要的。

在挖掘之后,我设法将输出输出到日志文件中,如下所示:

from ansible import constants as C
C.DEFAULT_LOG_PATH = 'project.log'
reload(callbacks)

但我需要在我的代码中访问它。

1 个答案:

答案 0 :(得分:4)

您可能无法获得所需的json格式,但您可以通过扩展回调类并将自己的处理程序编写到您感兴趣的事件中来获取相同的信息。

还要确保将类提供给Playbook实例,如下所示:

pb = ansible.playbook.PlayBook(
    ... # basic info
    callbacks= playbook_cb,
    runner_callbacks=runner_cb
)        

链接:

修改 在这种情况下,解决方案是扩展AggregateStat类。下面的代码示例由@Tom_Sawyyer提供

from ansible.callbacks import AggregateStats                                 

class CustomAggregateStats(AggregateStats):                                         
"""                                                                             
Holds stats about per-host activity during playbook runs.                       
"""                                                                             
def __init__(self):                                                             
    super(CustomAggregateStats, self).__init__()                                
    self.results = {}                                                           

def compute(self, runner_results, setup=False, poll=False,                      
            ignore_errors=False):                                               
    """                                                                         
    Walk through all results and increment stats.                               
    """                                                                         
    super(CustomAggregateStats, self).compute(runner_results, setup, poll,   
                                              ignore_errors)                    

    for (host, value) in runner_results.get('contacted', {}).iteritems():       
        if 'invocation' in value:                                               
            if value['invocation']['module_name'] == 'service':            
                self.results['service_name'] = value['name']                        

def summarize(self, host):                                                      
    """                                                                         
    Return information about a particular host                                  
    """                                                                         
    summarized_info = super(CustomAggregateStats, self).summarize(host)         

    # Adding the info I need                                                    
    summarized_info['result'] = self.results                                    

    return summarized_info

最后:

my_stats = CustomAggregateStats()
pb = ansible.playbook.PlayBook(
    ... # basic info
    stats=my_stats,
)     

给出输出:

{"127.0.0.1": {"skipped": 0, "ok": 3, "changed": 2, "result": {"service_name": "apache2"}, "failures": 0, "unreachable": 0}}