Ansible如何按键删除组值

Ansible how to remove groups value by key

我正在玩游戏,我将在 运行 任务之前收集可用的主机名,我使用它是有目的的,

我的游戏密码:

    --
    - name: check reachable side A hosts
      hosts: ????ha???
      connection: local
      gather_facts: no
      roles:
        - Juniper.junos
      vars:
        credentials:
          host: "{{ loopback_v4 }}"
          username: "test"
          ssh_keyfile: "/id_rsa"
          port: "{{ port }}"
          timeout: 60
      tasks:
        - block:
          - name: "Check netconf connectivity with switches"
            juniper_junos_ping:
              provider: "{{ credentials }}"
              dest: "{{ loopback_v4 }}"
          - name: Add devices with connectivity to the "reachable" group
            group_by:
              key: "reachable_other_pairs"
          rescue:
            - debug: msg="Cannot ping to {{inventory_hostname}}. Skipping OS Install"
  

当我使用

打印这个时
- debug:
      msg: "group: {{ groups['reachable_other_pairs'] }}"

我低于结果

"this group : ['testha1', 'testha2', 'testha3']",

现在,如果使用相同密钥分组的不同主机再次调用相同的游戏,我将获得附加到现有值的新主机名,如下所示

- name: check reachable side B hosts
  hosts: ????hb???
  connection: local
      gather_facts: no
      roles:
        - Juniper.junos
      vars:
        credentials:
          host: "{{ loopback_v4 }}"
          username: "test"
          ssh_keyfile: "/id_rsa"
          port: "{{ port }}"
          timeout: 60
  tasks:
    - block:
      - name: "Check netconf connectivity with switches"
        juniper_junos_ping:
          provider: "{{ credentials }}"
          dest: "{{ loopback_v4 }}"
      - name: Add devices with connectivity to the "reachable" group
        group_by:
          key: "reachable_other_pairs"
      rescue:
        - debug: msg="Cannot ping to {{inventory_hostname}}. Skipping OS Install"

如果我打印 reachable_other_pairs 我得到的结果低于

"msg": " new group: ['testhb1', 'testhb2', 'testhb3', 'testha1', 'testha2', 'testha3']"

我只想要前 3 个条目 ['testhb1', 'testhb2', 'testhb3']

有人可以告诉我如何实现吗?

将此作为任务添加到您的块之前。它将刷新您的库存并清理所有不在其中的组:

- meta: refresh_inventory