【规则解释-共享】忽视错误

这篇文章是Ansible lint Advent Calendar 2022的第20天的文章。

这次我将解释关于规则 ignore-errors。

忽略错误

通过给ansible.builtin.command模块和ansible.builtin.shell模块应用ignore-errors指令,以验证在执行命令时是否会忽略错误。

尽管命令返回了“failed”,但忽略该错误可能会隐藏实际的失败,错误地输出任务失败,或导致意外的副作用和行为。

只需一个选项:

需要注意的是,ignore-errors指示只会忽略命令执行时的错误,而不会忽略语法错误、连接错误或文件不存在等与命令执行无关的错误。这些错误将会被保留并显示为错误。

有问题的代码

---
- name: Example playbook
  hosts: all
  tasks:
    - name: Run apt-get update
      ansible.builtin.command: apt-get update
      ignore_errors: true # <- コマンドのエラーを全て無視する設定になっている

修正后的代码1

给 “{{ansible_check_mode}}” 添加并忽略错误。

---
- name: Example playbook
  hosts: all
  tasks:
    - name: Run apt-get update
      ansible.builtin.command: apt-get update
      ignore_errors: "{{ ansible_check_mode }}" # <- Ignores errors in check mode.

修复后的代码2

将错误信息注册到变量中。

---
- name: Example playbook
  hosts: all
  tasks:
    - name: Run apt-get update
      ansible.builtin.command: apt-get update
      ignore_errors: true
      register: ignore_errors_register # <- エラー情報を変数へ登録する

修正后的代码3

定义一个条件,在给予指令时出现错误。

有一些博客文章表明这种写法似乎是最好的。我认为最好的方式是不使用ignore-errors指令并以这种方式进行处理。

---
- name: Example playbook
  hosts: all
  tasks:
    - name: Disable apport
      become: "yes"
      lineinfile:
        line: "enabled=0"
        dest: /etc/default/apport
        mode: 0644
        state: present
      register: default_apport
      failed_when: default_apport.rc !=0 and not default_apport.rc == 257 # <- エラーになる条件を定義する.

请参考以下网站

    • ignore-errors — Ansible Lint Documentation

 

    • Error handling in playbooks — Ansible Documentation

 

    • Validating tasks: check mode and diff mode — Ansible Documentation

 

    Ansible ignore_errors are evil – Sorin Sbarnea’s Crib / Ansible lintのメインコントリビューターの記事
广告
将在 10 秒后关闭
bannerAds