2016-08-12 61 views
1

如何捕獲ansible劇本中的任務失敗,因此運行失敗?捕獲結構中的Ansible錯誤

我使用fabric來包裝ansible-playbook命令,這是我目前使用的。

command = local(
    "sudo ansible-playbook %s --extra-vars \"project=%s role=%s env=%s version=%s enterprise=%s\"" 
    " --private-key ../inventory/keys/%s" % 
    (playbook, project, role, environment, version, enterprise, enterprise), capture=True) 
if command: 
    if command.stderr: 
     print(cyan(command.stderr)) 
    else: 
     print(green(command.stdout)) 
     print(blue("\nConfigured %s [%s] in %s stack" % 
        (project, role, environment))) 
else: 
    print(red("\nError configuring %s cloudformation resource stack:::: %s" 
       % role, command.stderr)) 

正如你可以看到我有命令,我捕獲輸出。 問題在於command.stderr只發生在ansible-playbook命令失敗的情況下,例如ansible無法連接到主機等,但在劇本中的task失敗時纔會發生。當發生這種情況時,我的代碼仍認爲命令實際上已成功完成

下面的例子; (這是不被command.stderr捕獲)

TASK [example.cloudformation : Launch cloudformation template] **************** 
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: TemplateSyntaxError: expected name or number 
fatal: [127.0.0.1]: FAILED! => {"failed": true, "msg": "Unexpected failure during module execution.", "stdout": ""} 
    to retry, use: --limit @example_stack_launch.retry 

我猜這與ansible callbacks做,但不知道如何公開和使用它們。

回答

0

可能的解決方案之一是將stdout_callback=json設置爲合理的配置。
在這種情況下,所有劇本的輸出都將採用機器可讀的json格式,因此您可以檢查錯誤。