如何在Ansible的block模块中使用多个with_items实现多循环配置?
解答
Ansible完全支持在同一个Play的不同任务中分别使用with_items,你遇到的运行异常并非多个with_items冲突导致,而是代码存在两处明确错误:
- 关键字拼写错误:assert任务中的循环关键字你写成了
with_item,少了末尾的s,正确语法为with_items,这是直接触发报错的核心原因。 - 断言逻辑错误:第一个任务是循环4个配置项分别执行grep,注册的
data_captured.results列表中,每一条结果仅对应单次grep的单个配置项,你当前要求每个item.stdout中同时存在4个配置项,逻辑完全不成立,必然会断言失败触发rescue逻辑。
修正后的可运行代码
# 公共配置项提取成变量,避免重复编写 vars: sysctl_configs: - 'net.ipv6.conf.all.disable_ipv6 = 1' - 'net.ipv6.conf.default.disable_ipv6 = 1' - 'net.ipv6.conf.lo.disable_ipv6 = 1' - 'vm.swappiness = 1' - name: Test with with_items block: - name: Searching several string command: grep -w "{{item}}" /root/test/sysctl.conf register: data_captured with_items: "{{ sysctl_configs }}" # 避免grep无匹配就直接中断,交给assert统一判断结果 failed_when: false - assert: that: - item.rc == 0 success_msg: "{{ item.item }} 已在文件中定义" fail_msg: "{{ item.item }} 未在文件中定义" with_items: '{{ data_captured.results }}' rescue: - name: Insert/Update /root/test/sysctl.conf blockinfile: path: /root/test/sysctl.conf block: | {% for config in sysctl_configs %} {{ config }} {% endfor %}
更优方案推荐
你这个场景完全不需要用两次循环+block/rescue的复杂逻辑,直接用Ansible原生模块就能实现配置项的幂等校验和写入,无需自行做grep判断:
- name: 配置sysctl参数 sysctl: name: "{{ item.key }}" value: "{{ item.value }}" state: present sysctl_file: /root/test/sysctl.conf reload: no with_items: - { key: 'net.ipv6.conf.all.disable_ipv6', value: '1' } - { key: 'net.ipv6.conf.default.disable_ipv6', value: '1' } - { key: 'net.ipv6.conf.lo.disable_ipv6', value: '1' } - { key: 'vm.swappiness', value: '1' }
内容的提问来源于stack exchange,提问作者dahwild
相关产品推荐
相关产品推荐

