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

如何配置Ansible Playbook,仅在python2解释器下执行bar任务?

解决方法

首先修正Playbook的缩进错误(原代码中hosts行缺少正确的缩进层级),再给bar任务添加正确的when条件判断即可实现需求。

正确的Playbook配置

---
- hosts: "{{ ansible_limit | default(omit) }}"
  vars:
    ansible_python_interpreter: "/usr/bin/python3"
  tasks:
    - name: foo
      shell: /home/test/foo
    - name: bar
      shell: /home/test/bar
      # 用in操作符判断字符串是否包含python2,写法简洁直观
      when: "'python2' in ansible_python_interpreter"

备选的find写法(同样有效)

如果偏好使用字符串find方法,确保语法正确即可:

when: ansible_python_interpreter.find('python2') != -1

问题排查要点

若仍无法正确访问变量,检查以下内容:

  • 确保Playbook的YAML缩进完全合规(YAML对缩进敏感,一般使用2个空格层级)
  • 确认ansible_python_interpreter变量的定义位置正确(当前play的vars下,或外部传入的全局变量)
  • 若通过命令行传入该变量(如ansible-playbook -e "ansible_python_interpreter=/usr/bin/python2"),验证变量传递是否正确

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 20:40:00