Ansible中如何在when条件语句中转义冒号:?
解决Ansible when条件含冒号引发的YAML语法错误与ansible-lint问题
问题根源
YAML解析器会把冒号加空格(: )识别为键值对的分隔符,哪怕这个冒号在单引号里,也可能触发语法错误;而用{{}}包裹条件又会违反ansible-lint的no-jinja-when规则。下面是几种不违反规则又能解决问题的办法:
办法1:用双引号包裹整个when表达式
给整个when条件套一层双引号,明确告诉YAML这是一个完整的字符串表达式,不会解析内部的冒号:
--- - name: Check variable starts with substring hosts: all tasks: - name: Verify variable ansible.builtin.debug: msg: "{{ item }}" when: "item.startswith('Model : ')" with_items: - "Model : Server 1" - "Other Item" - "Model : Server 2"
这种写法既符合YAML语法,又没用到多余的Jinja2模板标记,能通过ansible-lint检查。
办法2:把带冒号的前缀抽成变量
把包含冒号的前缀定义成变量,在when条件里直接引用变量,彻底避开冒号的语法问题:
--- - name: Check variable starts with substring hosts: all vars: target_prefix: "Model : " tasks: - name: Verify variable ansible.builtin.debug: msg: "{{ item }}" when: item.startswith(target_prefix) with_items: - "Model : Server 1" - "Other Item" - "Model : Server 2"
这种方式还能提升代码的可维护性,后续要修改前缀直接改变量就行。
办法3:改用正则表达式匹配
用Ansible的match测试配合正则表达式,匹配字符串开头的指定内容,同样用双引号包裹条件:
--- - name: Check variable starts with substring hosts: all tasks: - name: Verify variable ansible.builtin.debug: msg: "{{ item }}" when: "item is match('^Model : .*')" with_items: - "Model : Server 1" - "Other Item" - "Model : Server 2"
正则里的^表示匹配字符串起始位置,效果和startswith完全一致,同时能让YAML正确解析条件。
内容的提问来源于stack exchange,提问作者Costales
相关产品推荐
相关产品推荐

