如何让Ansible lineinfile模块任务仅在指定条件下执行?
解决方案
当然可以实现,只需要给任务添加when条件判断,同时修正原任务里的语法问题(原任务的name写法不符合Ansible规范)。以下是修改后的完整Playbook任务:
- name: 记录非特定结果的授权日志 lineinfile: create: true path: /tmp/grant.log line: >- {{ '%Y-%m-%d %H:%M:%S'|strftime() }} {{ item }} {{ hostvars[item].results_grant.stdout }} loop: "{{ ansible_play_hosts }}" delegate_to: localhost run_once: true ignore_errors: true when: - hostvars[item].results_grant is defined - hostvars[item].results_grant.stdout != "你的特定值"
关键修改说明:
- 修正语法问题:原任务把
name和lineinfile模块写在同一行,不符合Ansible的YAML语法规范,调整为name单独作为任务名称,模块缩进在其下方。 - 添加条件判断:通过
when关键字设置两个判断条件:- 先确保
results_grant变量已定义,避免因变量不存在导致任务报错; - 核心判断:仅当
stdout不等于你指定的特定值时,才执行该日志记录任务。把"你的特定值"替换成实际需要排除的内容即可(比如"授权成功"这类字符串)。
- 先确保
- 其他原有参数(
loop、delegate_to等)保持不变,确保原有功能逻辑不受影响。
内容的提问来源于stack exchange,提问作者user20860852
相关产品推荐
相关产品推荐

