Ansible中如何将多个条件合并到单个when语句?
Ansible多条件判断语法修正
问题场景
使用Ansible 2.10.x版本,需求为:当变量web_version既不包含"development"也不包含"feature"子串时,执行set_fact任务覆盖默认的repo_url。但原有条件写法在执行ansible-playbook ... -e web_version=development_ myTask.yml时,set_fact意外执行,不符合预期。
原有错误写法:
# tasks/main.yml 中错误的条件 - name: Override default path set_fact: repo_url: "https://someUrl/releases" when: ('"development" not in web_version') and ('"feature" not in web_version')
错误原因
条件中的引号嵌套错误:将需要匹配的子串development用双引号包裹后又套了单引号,导致Ansible解析时会去匹配带双引号的子串"development",而非纯文本development。当传入web_version=development_时,变量值中不存在带双引号的子串,因此条件判断为true,意外触发了set_fact任务。
正确写法
以下两种写法均可实现需求,推荐使用列表形式的条件,可读性更强:
写法一:列表形式(逻辑与默认生效)
- name: Override default path set_fact: repo_url: "https://someUrl/releases" when: - "'development' not in web_version" - "'feature' not in web_version"
写法二:and连接的单行/多行写法
# 单行写法 - name: Override default path set_fact: repo_url: "https://someUrl/releases" when: "'development' not in web_version and 'feature' not in web_version" # 多行写法 - name: Override default path set_fact: repo_url: "https://someUrl/releases" when: "'development' not in web_version" and "'feature' not in web_version"
验证说明
- 当传入
web_version=development_时,'development' in web_version结果为true,因此'development' not in web_version为false,整个条件不成立,set_fact不会执行; - 当传入
web_version=v2.0.0(不含目标子串)时,两个条件均为true,set_fact执行,repo_url被覆盖为https://someUrl/releases。
内容的提问来源于stack exchange,提问作者Chris F
相关产品推荐
相关产品推荐

