ansible:在 when 语句中访问最后一个清单列表 item/list 大小

ansible: accessing last inventory list item/list size within when statement

我尝试检查 when 语句中的三重条件,如下所示:

# Run only on the last of the oct_servers (once all the others have been launched) and only when there are at least 2 servers

when: (container_state == "started" and ansible_host == {{ groups['oct_servers'] | last }} and {{ groups['oct_servers'] | length }} > 1 )

但它失败了,并出现警告,指出不应在 when 语句中使用 {{ }} 和 {% %}。我把它排除在外,并尝试了许多可能的组合,但没有成功。上述条件的正确语法是什么?

只需删除 Jinja 定界符即可:

when: container_state == "started" and ansible_host == groups['oct_servers'] | last and groups['oct_servers'] | length > 1

注意 when 条件需要多个条件都为真 can also be expressed as a list:

when: 
  - container_state == "started"
  - ansible_host == groups['oct_servers'] | last
  - groups['oct_servers'] | length > 1