首页 > 解决方案 > Ansible:计算元素并用于条件检查

问题描述

我有一本剧本,用于 key: value 定义,如下所示:

x_interfaces:
  - eno1
  - eno2

在另一本剧本中(包括那个剧本,我想进行条件检查,如下所示:

- name: debug message
  debug:
    msg: There is more then 1 interface in the machine
  when: x_interfaces|length > '1'

但它不起作用。我收到此错误消息:

The error was: Unexpected templating type error occurred on ({% if x_interfaces|length > '1' %} True {% else %} False {% endif %}): '>' not supported between instances of 'int' and 'str'

我究竟做错了什么?如果我使用x_interfaces|int > '1'它也会失败。

标签: ansibleyaml

解决方案


length返回一个整数。'1'是一个字符串。正如错误消息指出的那样,比较不能在字符串和整数之间执行操作。

为此,您只需更改'1'1. 您现在正在将整数与整数进行比较。

- name: debug message
  debug:
   msg: There is more then 1 interface in the machine
  when: x_interfaces|length > 1

推荐阅读