0

我有以下复杂的字典(这只是一个示例)。我正在尝试获取属于 server1 的所有 id 的列表。server1 的名称大小写不一。

我尝试了类似match,的 jinja2 过滤器searchequalto但它们都没有返回预期结果。还尝试了 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\") }}"
4

1 回答 1

1

这可以通过loweransible 的 when 和 filter 来实现。下面的剧本对我有用。

剧本:

- 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

希望这会有所帮助

于 2020-04-24T06:14:40.160 回答