简体   繁体   English

从包含来自 ansible 的特定测试的列表中获取一个项目

[英]Fetch an item from the list containing specific test from ansible

I need to filter items contain "TEST" in the below mentioned list,我需要在下面提到的列表中过滤包含“TEST”的项目,

ok: [localhost] => {
    "msg": [
        "TEST_Automation",
        "TEST-LAB",
        "PROD-Common",
        "LAB-IT",
        "TEST-Core",
        "NutanixESX",
        "NutanixLAB",
        "TEST-LaaS",
        "Projects"
    ]
}

I use the bellow command to get the above mentioned list:我使用以下命令获取上述列表:

    - debug:
        msg: "{{ cluster_info.clusters.keys() | list }}"

Tried selectattr or lookup but I'm unable to write correct syntax to grep the items containing "TEST".尝试了 selectattr 或查找,但我无法将正确的语法写入 grep 包含“TEST”的项目。 Any suggestion as I use old community version I cannot use items2dict.我使用旧社区版本时的任何建议都不能使用 items2dict。

selectattr doesn't make any sense because you have a simple list of strings (the items don't have attributes). selectattr没有任何意义,因为您有一个简单的字符串列表(这些项目没有属性)。 lookup makes even less sense because that's for creating generating new information from some sort of query (like reading the lines from a file, or reading an environment variable, etc). lookup更没有意义,因为它是为了从某种查询中生成新信息(比如从文件中读取行,或读取环境变量等)。

If you want to select items from a list based on some sort of criteria, you want the select filter :如果您想根据某种标准从列表中获取 select项目,则需要select过滤器

Filters a sequence of objects by applying a test to each object, and only selecting the objects with the test succeeding.通过对每个 object 应用测试来过滤一系列对象,并仅选择测试成功的对象。

That would look something like:这看起来像:

cluster_info.clusters.keys() | select('match', 'TEST')

Here we're using the match test , which "succeeds if it finds the pattern at the beginning of the string".这里我们使用了match test ,它“如果在字符串的开头找到了模式就成功了”。

A runnable example:一个可运行的例子:

- hosts: localhost
  gather_facts: false
  vars:
    cluster_info:
      clusters:
        "TEST_Automation": {}
        "TEST-LAB": {}
        "PROD-Common": {}
        "LAB-IT": {}
        "TEST-Core": {}
        "NutanixESX": {}
        "NutanixLAB": {}
        "TEST-LaaS": {}
        "Projects": {}

  tasks:
    - debug:
        msg: "{{ cluster_info.clusters.keys() | list | select('match', 'TEST') }}"

The above example outputs:上面的示例输出:


PLAY [localhost] ***************************************************************

TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": [
        "TEST_Automation",
        "TEST-LAB",
        "TEST-Core",
        "TEST-LaaS"
    ]
}

PLAY RECAP *********************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM