Ansible来自/ etc / ansible / hosts的五台随机主机

时间:2018-07-13 22:29:31

标签: ansible ansible-2.x ansible-inventory

我有这本剧本,它使用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

2 个答案:

答案 0 :(得分:0)

解决方案

您需要重新排列组的元素,然后首先选择三个。 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:

答案 1 :(得分:0)

这样的事情怎么办?

---
- 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

  

注意:出于学习目的,我将剧本保留为connection:ciscos而不是localhost并显示了ansible_play_batchmax_index变量。最好让本地主机玩groups而不是delegate_to:localhost