You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible如何基于前序任务输出设置when条件执行后续任务

问题原因
  • service_status.stdout_lines 返回的是列表类型,你直接将列表和字符串做相等判断,结果必然为假,所以目标任务始终被跳过。
  • == "Status*running" 这种写法不符合Ansible条件判断的语法规则,== 是精确相等匹配,不支持通配符匹配逻辑,你之前修改后的写法引号嵌套错误,所以触发语法报错。
正确的when条件写法

根据你的需求,可选以下任意一种符合场景的写法:

  1. 只要任意一行状态包含running就执行(最通用,推荐)
when: "'running' in service_status.stdout"
  1. 严格匹配列表中存在Status: running元素才执行
when: "'Status: running' in service_status.stdout_lines"
  1. 用正则匹配状态格式(支持忽略大小写等扩展需求)
when: service_status.stdout is search('Status.*running', ignorecase=True)
修改后的完整playbook示例
- name: 'Backup'
  hosts: localhost
  tasks:
    - name: 'Check_Status'
      shell: tool ha status |grep -i Status
      register: service_status

    - debug:
        var: service_status.stdout_lines

    - name: 'Run ls'
      shell: ls -ltr
      when: "'running' in service_status.stdout"
      register: output

    - debug:
        var: output

内容的提问来源于stack exchange,提问作者manoscorne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 11:06:05