- name: Start service bar and enable it ansible.builtin.service: name: bar state: started enabled: True become: true become_user: root ignore_errors: true
tasks: - name: Handle the error block: - name: Print a message ansible.builtin.debug: msg: 'I execute normally'
- name: Force a failure ansible.builtin.command: /bin/false
- name: Never print this ansible.builtin.debug: msg: 'I never execute, due to the above task failing, :-(' rescue: - name: Print when errors ansible.builtin.debug: msg: 'I caught an error, can do stuff here to fix it, :-)'
tasks: - name: Always do X block: - name: Print a message ansible.builtin.debug: msg: 'I execute normally'
- name: Force a failure ansible.builtin.command: /bin/false
- name: Never print this ansible.builtin.debug: msg: 'I never execute :-(' always: - name: Always do this ansible.builtin.debug: msg: "This always executes, :-)"
这些元素共同提供了复杂的错误处理。
带有所有部分的块
tasks: - name: Attempt and graceful roll back demo block: - name: Print a message ansible.builtin.debug: msg: 'I execute normally'
- name: Force a failure ansible.builtin.command: /bin/false
- name: Never print this ansible.builtin.debug: msg: 'I never execute, due to the above task failing, :-(' rescue: - name: Print when errors ansible.builtin.debug: msg: 'I caught an error'
- name: Force a failure in middle of recovery! >:-) ansible.builtin.command: /bin/false
- name: Never print this ansible.builtin.debug: msg: 'I also never execute :-(' always: - name: Always do this ansible.builtin.debug: msg: "This always executes"
tasks: - name: Attempt and graceful roll back demo block: - name: Print a message ansible.builtin.debug: msg: 'I execute normally' changed_when: true notify: Run me even after an error
- name: Force a failure ansible.builtin.command: /bin/false rescue: - name: Make sure all handlers run meta: flush_handlers handlers: - name: Run me even after an error ansible.builtin.debug: msg: 'This handler runs even on error'
tasks: - name: Attempt and graceful roll back demo block: - name: Do Something ansible.builtin.shell: grep $(whoami) /etc/hosts
- name: Force a failure, if previous one succeeds ansible.builtin.command: /bin/false rescue: - name: All is good if the first task failed when: ansible_failed_task.name == 'Do Something' ansible.builtin.debug: msg: All is good, ignore error as grep could not find 'me' in hosts
- name: All is good if the second task failed when: "'/bin/false' in ansible_failed_result.cmd | d([])" ansible.builtin.fail: msg: It is still false!!!