当条件根据 Azure DevOps 管道的 Ansible 任务中的主机名



>主机名通常看起来像vcs-200-01。因此,当主机名具有 vcs 或 vhs 任务时,应该运行。我已经尝试了下面的任务,但它在所有虚拟机上运行,而不是在特定 VM 上运行

- name:Exceute shell script
become:yes
become_user:root
become_method:sudo
command: sh /usr/..../example.sh
when:("'vcs' in inventory_hostname_short") or ("'vhs' in inventory_hostname_short")

问题是括号内逻辑表达式的引用。这些表达式不计算,而是作为字符串获取。非空字符串的计算结果为True。这就是条件始终为True的原因。

when: ("'vcs' in inventory_hostname_short") or
("'vhs' in inventory_hostname_short")

解决方案很简单。删除报价。例如任务

- debug:
var: inventory_hostname_short
when: ('vcs' in inventory_hostname_short) or
('vhs' in inventory_hostname_short)

和库存

shell> cat hosts
vcs-200-01
vhs-200-01
vxs-200-01

ok: [vcs-200-01] => 
inventory_hostname_short: vcs-200-01
ok: [vhs-200-01] => 
inventory_hostname_short: vhs-200-01
skipping: [vxs-200-01]


此错误的起源可能是 YAML 解析器要求报价。例如
when: 'vcs' in inventory_hostname_short
ERROR! Syntax Error while loading YAML.
did not find expected key
The error appears to be in '/export/scratch/tmp/test-42.yml': line 10, column 19, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
msg: vcs
when: 'vcs' in inventory_hostname_short
^ here
This one looks easy to fix. It seems that there is a value started
with a quote, and the YAML parser is expecting to see the line ended
with the same kind of quote. For instance:
when: "ok" in result.stdout
Could be written as:
when: '"ok" in result.stdout'
Or equivalently:
when: "'ok' in result.stdout"

推荐报价解决问题

when: "'vcs' in inventory_hostname_short"  # OK

括号中的结束也是如此

when: ('vcs' in inventory_hostname_short)  # OK

但不是括号和引文

when: ("'vcs' in inventory_hostname_short")  # WRONG

表达式

when: 'vcs' in inventory_hostname_short or
'vhs' in inventory_hostname_short

将产生类似的错误和相同的建议

The offending line appears to be:
var: inventory_hostname_short
when: 'vcs' in inventory_hostname_short or
^ here
Could be written as:
when: '"ok" in result.stdout'
Or equivalently:
when: "'ok' in result.stdout"

但是在这里,推荐的解决方案将不起作用,并且会产生相同的错误和相同的建议


when: "'vcs' in inventory_hostname_short" or
"'vhs' in inventory_hostname_short"

括号中必须以括号括起来的逻辑表达式

when: ('vcs' in inventory_hostname_short) or
('vhs' in inventory_hostname_short)

那么条件可以选择引用

when: "('vcs' in inventory_hostname_short) or
('vhs' in inventory_hostname_short)"

最新更新