如何为Ansible中不满足when条件跳过的任务设置自定义提示消息?
解决方案
1. 优化文件存在性判断变量
首先修正第一个Playbook中exists变量的定义,原逻辑返回列表格式,需转换为布尔值以便后续判断:
- name: Search for files win_find: paths: C:\dataset\ register: data - name: Set file existence flag set_fact: exists: "{{ data.files | length > 0 }}"
说明:
win_find返回的files数组,若存在匹配文件则不为空,通过length > 0直接判断文件是否存在,结果为True或False。
2. 在第二个Playbook中实现自定义消息输出
不要直接引用被跳过任务的day变量,改用条件分支分别处理两种场景:
- name: Run if file exists block: - name: Read content from file win_shell: type C:\day.txt # 用type命令读取文本文件内容,原命令会直接执行文件 register: day when: hostvars['10.11.18.190']['exists'] - name: Print custom message debug: msg: >- {% if hostvars['10.11.18.190']['exists'] %} {{ day.stdout }} {% else %} 文件不存在 {% endif %}
3. 可选:处理变量未定义的边界情况
若担心day因任务被跳过未定义导致报错,可增加变量存在性检查:
- name: Print custom message with fallback debug: msg: >- {% if hostvars['10.11.18.190']['exists'] and day is defined %} {{ day.stdout }} {% else %} 文件不存在 {% endif %}
内容的提问来源于stack exchange,提问作者Whaily
相关产品推荐
相关产品推荐

