如何根据变量对库存进行排序?

时间:2017-10-04 00:08:48

标签: cassandra ansible

我有ansible库存文件如下:

[dc1]
dc1-node0 ansible_host=10.1.0.1 seed=no
dc1-node1 ansible_host=10.1.0.2 seed=yes 
dc1-node2 ansible_host=10.1.0.2 seed=yes 
[dc2]
dc2-node ansible_host=10.2.0.1 seed=yes
dc2-node1 ansible_host=10.2.0.2 seed=no
dc2-node2 ansible_host=10.2.0.2 seed=yes

我需要编写一个Playbook,它首先启动种子节点,然后启动其他节点。 同样,用户也可以只提供一个节点。所以我的剧本应该能够检查它是种子还是非种子,并做相应的事情。

到目前为止,我能够按如下方式编写剧本:

- hosts:  "{{ dbhosts }}"
  serial: 1
  vars:
  vars_prompt:
  - name: "dbhosts"
    prompt: "Which hosts would you like to run?"
    private: no
  gather_facts: no
  tasks:
  - name: is dse already running?
    shell: service dse status | grep dead | wc -l
    register: svc_dse_dead
    ignore_errors: true
  - debug:
       msg: "Is DSE service dead (0 = No; 1 = Yes)? Current status =  {{svc_dse_dead.stdout}}"
  - name: Start dse service
    service:
      name: dse
      state: started
    become: true
    become_method: sudo
    when:
         - svc_dse_dead.stdout == "1"        
  - name: Pausing execution to stablize gossipping between nodes
    pause:
      minutes: 2
    when:  
      svc_dse_dead.stdout == 1 

但是这个剧本并没有基于种子节点对主机进行排序。 有什么办法可以实现吗? 请告知一些想法。

由于

1 个答案:

答案 0 :(得分:0)

例如,您可以生成动态组:

---
- hosts: all
  gather_facts: no
  tasks:
    - group_by:
        key: "seed_{{ 'yes' if seed | default(false,boolean=true) | bool else 'no' }}"

- hosts: seed_yes:seed_no
  gather_facts: no
  serial: 1
  tasks:
    - debug: msg="{{ seed | default('unknown') }}"

serial: 1在这里至关重要,因为seed_yes:seed_no模式将确保yes - 主机位于首位,因此我们应该逐个迭代它们。

如果需要速度,您可以避免serial,但必须创建两个相同的游戏 - 一个用于yes,另一个用于no

---
- hosts: all
  gather_facts: no
  tasks:
    - group_by:
        key: "seed_{{ 'yes' if seed | default(false,boolean=true) | bool else 'no' }}"

- hosts: seed_yes
  gather_facts: no
  tasks:
    - debug: msg="{{ seed | default('unknown') }}"

- hosts: seed_no
  gather_facts: no
  tasks:
    - debug: msg="{{ seed | default('unknown') }}"