错误是:评估条件时出错

The error was: error while evaluating conditional

我尝试使用 Ansible 向我拥有的每台服务器插入一个唯一编号。

如下,我希望这些是:

192.168.60.6 中的“1”myid.txt

192.168.60.7 中的“2”myid.txt

- hosts: all
  gather_facts:True
  vars:
    servers:
      host1:
        ip: 192.168.60.6
        num: 1
      host2:
        ip: 192.168.60.7
        num: 2
      host3:
        ip: 192.168.60.8
        num: 3

  tasks:
    -name: write a unique number in myid.txt 
     lineinfile:
       dest: "/home/user/myid.txt"
       line: "{{ item.value.num }}"
     when: "{{ item.value.ip }} == {{ ansible_all_ipv4_addresses[1] }}"
     `enter code here`with_dict: "{{ servers }}"

不幸的是,我遇到了这个错误:

TASK [write unique number in myid] 

*********************************************
fatal: [192.168.60.6]: FAILED! => {"failed": true, "msg": "The conditional check '{{item.value.ip}} == {{ ansible_all_ipv4_addresses[1] }}' failed.   
The error was: error while evaluating conditional ({{item.value.ip}} == {{ ansible_all_ipv4_addresses[1] }}): float object has no element 60

The error appears to have been in '/home/shihhao/Desktop/BlueTech/ansible/kafka_playbook.yml': line 101, column 7,   
but may be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:
    - name: write unique number in myid
      ^ here\n"}

似乎一旦我添加这行我就会得到错误。

 when: "{{item.value.ip}} == {{ ansible_all_ipv4_addresses[1] }}"

顺便说一句:{{ ansible_all_ipv4_addresses[1] }} 是 192.168.60.6

您应该在 when: 语句中使用裸变量:

when: item.value.ip == ansible_all_ipv4_addresses[1]

来自documentation

This is easy to do in Ansible with the when clause, which contains a raw Jinja2 expression without double curly braces

原始表达式用于 when: 语句、assert 模块和 debug: var=varname (but debug: msg="{{varname}}")。