来自 /etc/ansible/hosts 的五个随机主机

Ansible Five random hosts from /etc/ansible/hosts

我有这本剧本,它使用 max_index 工作,但总是从 /etc/ansible/hosts 中获取前 3 个主机,我需要从该文件中随机获取 3 个(且不重复)主机。

playbook.yml

---
- hosts: ciscos
  connection: local
  gather_facts: false
  tasks:
    - group_by: key=limited_selection
      when: play_hosts.index(inventory_hostname) < max_index | int

- hosts: limited_selection
  gather_facts: no

/etc/ansible/hosts

[ciscos]
stagin ansible_host=10.xx.xx.1
stagin2 ansible_host=10.xx.xx.1
stagin3 ansible_host=10.xx.xx.1
stagin4 ansible_host=10.xx.xx.1
stagin5 ansible_host=10.xx.xx.1

解决方案

您需要对组中的元素进行洗牌,先选择三个。 Jinja2 表达式为:

(groups['ciscos'] | shuffle)[0:3]

应该有效但有问题的实施

您应该能够简单地过滤 hosts 声明中的组:

- hosts: "{{ (groups['ciscos'] | shuffle)[0:3] }}"
  gather_facts: no
  tasks:
    - debug:

然而,结果是不确定的 - 虽然游戏显示为 运行 针对三个随机选择的主机,但任务有时会在 1、2、3 或 0 上执行:

PLAY [[u'stagin2', u'stagin4', u'stagin5']] *******************************************************************************

TASK [debug] **************************************************************************************************************
ok: [stagin2] => {
    "msg": "Hello world!"
}
ok: [stagin5] => {
    "msg": "Hello world!"
}

解决方法(有效的实施)

使用 add_host 模块创建过滤组:

- hosts: localhost
  connection: local
  gather_facts: no
  tasks:
    - add_host:
        name: "{{ item }}"
        groups: limited_selection
      loop:  "{{ (groups['ciscos'] | shuffle)[0:3] }}"

- hosts: limited_selection
  gather_facts: no
  tasks:
    - debug:

这样的事情怎么样?

---
- hosts: ciscos
  gather_facts: False
  connection: local

  tasks:

    - name: Fact My Inventory
      set_fact:
        myinventory: "{{ ansible_play_batch | shuffle }}"
      run_once: True
      delegate_to: localhost

    - name: Fact limited_selection
      set_fact:
        limited_selection: "{{ myinventory[0:max_index|int] }}"
      run_once: True
      delegate_to: localhost

    - name: Create Inventory
      add_host:
        name: '{{ item }}'
        groups: limited_selection
      with_items: "{{ limited_selection }}"
      delegate_to: localhost

- hosts: limited_selection
  gather_facts: no

  tasks:
    - name: Debug
      debug:
        msg: "I'm in the limited selection group!"

小心 play_hosts,因为它已被弃用。

Note: I have kept the playbook with connection:ciscos instead of localhost for learning purposes and showing the ansible_play_batch and max_index variables. It is better to have a localhost play with groups instead of delegate_to:localhost