Ansible:忽略循环中的错误
Ansible: ignoring errors in a loop
我需要在 linux 个盒子上安装一些软件包。由于各种原因(OS 版本,本质上)
可能会丢失一些(少数)软件包
- vars:
pkgs:
- there_1
- not_there_1
- there_2
...
但我也想通过一个剧本来管理它们。所以我不能把它们全部粘在一个
yum: state=latest name="{{pkgs}}"
因为缺少软件包会扰乱交易,因此无法安装任何东西。
然而,明显的(和缓慢的)一个一个安装也失败了,因为第一个丢失的包把整个循环从水中吹了出来,因此:
- name Packages after not_there_1 are not installed
yum: state=latest name="{{item}}"
ignore_errors: yes
with_items: "{{ pkgs }}"
有没有一种方法可以忽略循环中的错误,让所有项目都有机会? (即安装错误在循环中表现为 continue
)
如果您需要在一个单元中循环执行一组任务,那么如果我们可以在错误处理块上使用 with_items 就太好了,对吗?
在该功能出现之前,您可以使用 include_tasks 和 with_items 完成同样的事情。这样做应该允许一个块来处理失败的包,或者如果你愿意,你甚至可以在 sub-tasks 中包括一些检查和包安装。
首先设置一个 sub-tasks.yml 来包含您的安装任务:
Sub-Tasks.yml
- name: Install package and handle errors
block:
- name Install package
yum: state=latest name="{{ package_name }}"
rescue:
- debug:
msg: "I caught an error with {{ package_name }}"
然后您的剧本将设置这些任务的循环:
- name: Install all packages ignoring errors
include_tasks: Sub-Tasks.yml
vars:
package_name: "{{ item }}"
with_items:
- "{{ pkgs }}"
我需要在 linux 个盒子上安装一些软件包。由于各种原因(OS 版本,本质上)
可能会丢失一些(少数)软件包 - vars:
pkgs:
- there_1
- not_there_1
- there_2
...
但我也想通过一个剧本来管理它们。所以我不能把它们全部粘在一个
yum: state=latest name="{{pkgs}}"
因为缺少软件包会扰乱交易,因此无法安装任何东西。
然而,明显的(和缓慢的)一个一个安装也失败了,因为第一个丢失的包把整个循环从水中吹了出来,因此:
- name Packages after not_there_1 are not installed
yum: state=latest name="{{item}}"
ignore_errors: yes
with_items: "{{ pkgs }}"
有没有一种方法可以忽略循环中的错误,让所有项目都有机会? (即安装错误在循环中表现为 continue
)
如果您需要在一个单元中循环执行一组任务,那么如果我们可以在错误处理块上使用 with_items 就太好了,对吗?
在该功能出现之前,您可以使用 include_tasks 和 with_items 完成同样的事情。这样做应该允许一个块来处理失败的包,或者如果你愿意,你甚至可以在 sub-tasks 中包括一些检查和包安装。
首先设置一个 sub-tasks.yml 来包含您的安装任务:
Sub-Tasks.yml
- name: Install package and handle errors
block:
- name Install package
yum: state=latest name="{{ package_name }}"
rescue:
- debug:
msg: "I caught an error with {{ package_name }}"
然后您的剧本将设置这些任务的循环:
- name: Install all packages ignoring errors
include_tasks: Sub-Tasks.yml
vars:
package_name: "{{ item }}"
with_items:
- "{{ pkgs }}"