在Ansible合并2组

时间:2017-03-02 10:34:45

标签: ansible

我的库存中有2个主机组,如下所示:

[loadbalancer-add]
172.23.130.97
172.23.130.98

[loadbalancer-remove]
172.23.130.99
172.23.130.100

我想合并这些组以将它们传递给loadbalancer API,以便我可以添加服务器,然后删除服务器。所以我需要合并组来创建一个组,如下所示:

[loadbalancer]
172.23.130.97
172.23.130.99
172.23.130.98
172.23.130.100

我有以下任务,但它没有产生正确的输出

- name: Merge Dictionaries
  gather_facts: false
  hosts: localhost
  become: true
  no_log: false

  tasks:
    - add_host:
        name: "{{ item }}"
        ansible_ssh_port: 2020
        action: remove
        group: loadbalancer
      with_items:
        - "{{ groups['loadbalancer-remove'] }}"
        - "{{ groups['loadbalancer-add'] }}"
      delegate_to: localhost

这会产生

[loadbalancer]
172.23.130.99
172.23.130.100
172.23.130.97
172.23.130.98

是否可以获得我需要的输出?

由于

2 个答案:

答案 0 :(得分:1)

我确实设法找到了这样做的方法。这可能不是最好的方法,但无论如何这是我的解决方案:

- name: Merge Dictionaries
  gather_facts: false
  hosts: localhost
  no_log: false

  vars:
    merged_lb_hosts: |
      {% if (groups['loadbalancer-add'] | length) >= (groups['loadbalancer-remove'] | length) %}
        {% for i in range(0, groups['loadbalancer-add'] | length) -%}
          {{ groups['loadbalancer-add'][i] | default('') }}:add|{{ groups['loadbalancer-remove'][i] | default('') }}:remove|
        {%- endfor %}
      {% else %}
        {% for i in range(0, groups['loadbalancer-remove'] | length) -%}
          {{ groups['loadbalancer-add'][i] | default('') }}:add|{{ groups['loadbalancer-remove'][i] | default('') }}:remove|
        {%- endfor %}
      {% endif %}

  tasks:
    - debug: msg="{{ merged_lb_hosts }}"
    - add_host:
        name: "{{ item.split(':')[0] }}"
        action: "{{ item.split(':')[1] }}"
        ansible_ssh_port: 2020
        group: loadbalancer
      with_items:
        - "{{ (merged_lb_hosts | trim()).split('|') }}"
      when: "{{item.split(':')[0] != ''}}"

这将使用添加和删除组并将它们合并到名为merged_lb_hosts

的var中

add_host任务会将此变量拆分为with_items部分,以创建可迭代列表。

感觉非常hacky但是它完成了我之后的工作

答案 1 :(得分:0)

可能这就是你需要的:

[loadbalancer-add]
172.23.130.97
172.23.130.98

[loadbalancer-remove]
172.23.130.99
172.23.130.100

[loadbalancer:children]
loadbalancer-remove
loadbalancer-add

所以现在你可以作为一个组引用

groups['loadbalancer']*