Ansible jinja2比较字符串的非大小写敏感度

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

我有以下复杂的字典(这只是一个例子)。我试图抓取一个属于服务器1的所有ID的列表。我尝试了jinja2的过滤器,如match, search, equalto,但都没有返回预期的结果。我也试过JSON查询,但还是不知道如何将小写或大写的比较工作。

---
- name: TEST
  hosts: localhost
  gather_facts: no

  vars:
    datacenters: {
      cabinets: {
        servers: [
          {
            name: Server1,
            id: 1
          },
          {
            name: SERVER1,
            id: 2
          },
          {
            name: Server2,
            id: 3
          },
          {
            name: server1,
            id: 4
          },
         ]
      }
    }

  tasks:
    - name: get ids for Server 1 
      set_fact:
        ids: "{{ datacenters.cabinets.servers
          | selectattr('name','match','Server1')
          | map(attribute='id')
          | list }}"

    - debug:
          var: ids

    - debug: msg="{{ datacenters | json_query(\"cabinets.servers[?name == 'Server1'].id\") }}"
string ansible comparison jinja2 json-query
1个回答
1
投票

这可以用when和 lower 过滤器的ansible。下面的玩法对我来说是可行的。

剧本。

- name: Demo of restore plan
  hosts: localhost
  gather_facts: False
  vars:
    datacenters: {
        cabinets: {
          servers: [
            {
              name: Server1,
              id: 1
            },
            {
              name: SERVER1,
              id: 2
            },
            {
              name: Server2,
              id: 3
            },
            {
              name: server1,
              id: 4
            },
          ]
        }
      }
  tasks:
    - debug:
        msg: "{{ item.name }}"
      with_items:
        - "{{ datacenters.cabinets.servers }}"
      when: item.name|lower == "server1"

输出:

[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'


PLAY [Demo of restore plan] ************************************************************************************************************************************************

TASK [debug] ***************************************************************************************************************************************************************
ok: [localhost] => (item={'name': 'Server1', 'id': 1}) => {
    "msg": "Server1"
}
ok: [localhost] => (item={'name': 'SERVER1', 'id': 2}) => {
    "msg": "SERVER1"
}
skipping: [localhost] => (item={'name': 'Server2', 'id': 3})
ok: [localhost] => (item={'name': 'server1', 'id': 4}) => {
    "msg": "server1"
}

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

Ansible只列出server1行,忽略server2行。

希望能帮到你

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