当救援块在文件中时,“ansible_failed_task”和“ansible_failed_result”变量未定义

Pa*_*hah 5 error-handling ansible ansible-playbook ansible-2.x

当在 Ansible 角色内部调用的文件中使用块救援完成错误处理时,ansible_failed_taskansible_failed_result变量会给出未定义的错误main.yml

文件夹结构:

roles/
  role-test/
    main.yml
    file_with_error_handling.yml
Run Code Online (Sandbox Code Playgroud)

main.yml

- include file_with_error_handling.yml
Run Code Online (Sandbox Code Playgroud)

file_with_error_handling.yml

- block:
    # some code with error.
  rescue:
    debug:
      msg: "Task- {{ ansible_failed_task }} failed with error {{ ansible_failed_result }}"
Run Code Online (Sandbox Code Playgroud)

test.yml

- hosts: all
  become: yes 
  roles:
    - role-test
Run Code Online (Sandbox Code Playgroud)

test.yml执行我得到下面的错误:

致命:[本地主机]:失败!=> {"failed": true, "msg": "字段 'args' 有一个无效值,它似乎包含一个未定义的变量。错误是:'ansible_failed_result' 未定义\n\n错误似乎是已经在 '/tmp/test/role-test/tasks/test_main.yml': line 32, column 6,但可能\n在文件中的其他地方,具体取决于确切的语法问题。\n\n有问题的行似乎是:\n\n# msg: \"ansible_failed_task- {{ ansible_failed_task }}\"\n - 调试:\n ^ 这里\n"}

我为ansible_failed_task变量得到了同样的错误。

如果我复制file_with_error_handling.ymlin的代码main.yml然后执行它,它工作正常。我得到了ansible_failed_result和 中的值ansible_failed_task。只有当我从文件中调用它时才会出现问题。

有没有办法可以显示这些变量的输出?

Luc*_*ier 0

我找到了一种解决方法,尝试创建两个文件,一个 block.yml 和一个rescue.yml。

主要.yml:

- block: - name: Your block tasks include: block.yml rescue: - name: Rescue task in case of error in block include: rescue.yml

块.yml:

# some code with error.

救援.yml:

debug: msg: "Task- {{ ansible_failed_task }} failed with error {{ ansible_failed_result }}"