如何解决 TemplateRuntimeError: Ansible 中没有名为 'equalto' 的测试?

问题描述 投票:0回答:2

Ansible v2.2.1.0

我有一个收集项目信息的任务,我为该任务设置了一个寄存器。比如我用jq来解析一个JSON文件,

hello.json
----------
{
    "name" : "hello file",
    "english" : "hello",
    "spanish" : "hola",
    "german" : "wie gehts"
}

- name: parse the hello.json file
  shell: |
      jq -r '.{{ item }}' < hello.json
  register: hellos
  with_items:
  - english
  - spanish
  - german

- debug: var=hellos

调试显示

ok: [localhost] => {
    "hellos": {
        "changed": true, 
        "msg": "All items completed", 
        "results": [
            {
                # snipped
                "item": "english", 
                "stdout" : "hello",
                # snipped
           },
            {
                # snipped
                "item": "spanish", 
                "stdout" : "hola",
                # snipped
           },
           {
                # snipped
                "item": "german", 
                "stdout" : "wie gehts",
                # snipped
           }
        ]
    }
}

现在如果我想获取 hellos 寄存器的标准输出值,我尝试了这个

- name: Display hello messages
  debug: msg="{{ hellos.results | selectattr("item","equalto",item) | map(attribute="stdout") | first }} worlld"
  with_items:
  - english
  - spanish
  - german

我明白了

An exception occurred during task execution. To see the full traceback, use -vvv. The error was: TemplateRuntimeError: no test named 'equalto'
fatal: [localhost]: FAILED! => {"failed": true, "msg": "Unexpected failure during module execution.", "stdout": ""}

我基本上是在第二个调试任务中解析“item”的 hellos 寄存器并获取其“stdout”属性。我的错误在哪里?

ansible ansible-2.x
2个回答
10
投票

你在这里做了一些非常奇怪的事情。我相信你原来的任务可以更容易地解决。

但是要回答你的问题“为什么

equalto
找不到过滤器?”:更新Jinja2。

请使用

pip list | grep Jinja2
进行检查。
equalto
在ver.1中引入。 2.8.


0
投票

Ansible 在 2.3 及更低版本中没有名为

equalto
的测试,因此您可以创建一个自定义测试插件名称
equal_to
。只需在 test_plugins 目录中创建一个文件即可。

#! /usr/bin/pyhton 
# vi ./test_plugins/anything.py
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

def equal_to(value, other):
  return value == other

class TestModule(object):
    def tests(self):
        return {
         'equal_to': equal_to
       }

快乐的发展...

© www.soinside.com 2019 - 2024. All rights reserved.