Ansible jinja2 比较不区分大小写的字符串

Ansible jinja2 compare strings non case sensitive

我有以下复杂词典(这只是一个示例)。我正在尝试获取属于 server1 的所有 ID 的列表。服务器 1 的名称大小写混合。

我尝试了 matchsearchequalto 等 jinja2 过滤器,但其中 none 个 returns 是预期的结果。还尝试了 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\") }}"

这可以通过ansible的when和lower过滤器来实现。下面的剧本对我有用。

剧本:

- 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

希望这对您有所帮助