节点列表中的项目取决于来自hostgroup

时间:2017-09-08 11:00:49

标签: ansible

我正在进行以下设置,

groups_var/all.yml
---
cassandra_restore:
  nodes:
   - 192.168.0.1
   - 192.168.0.2
   - 192.168.0.3


inventory contains,

[just_created]
192.168.0.4
192.168.0.5
192.168.0.6


main.yml

---
# playbook 


- name: setup
  hosts: just_created
  remote_user: ubuntu
  become: true
  become_method: sudo
  gather_facts: yes
  vars:
     current_index: "{{ ansible_play_batch.index(inventory_hostname) }}"
  tasks:
    - debug:
       msg: "current host index: {{ ansible_play_batch.index(inventory_hostname) }} : {{ current_index }}"
    - debug:
       msg: "first target host: {{ cassandra_restore.nodes.0 }}"
    - name: get mapped value
      debug:
       msg: "current target host: {{ cassandra_restore.nodes.current_index }} "

我想从节点列表中访问项目取决于来自hostgroup just_created的主机的当前索引。 因此,当主机为192.168.0.4时,它应打印192.168.0.1,当主机为192.168.0.5时,它应打印192.168.0.2,依此类推。

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

您必须使用地图表单来访问动态索引或键:

- name: get mapped value
  debug:
    msg: "current target host: {{ cassandra_restore.nodes[current_index] }} "

但我不确定主机的顺序是否具有确定性。

答案 1 :(得分:0)

---
# playbook for creating cassandra setup


- name: setup cassnadra
  hosts: just_created
  remote_user: ubuntu
  become: true
  become_method: sudo
  gather_facts: yes
  vars:
     current_index: "{{ ansible_play_batch.index(inventory_hostname) }}"
  tasks:
    - name: get mapped value
      debug:
        msg: "current_index current target host: {{ item.index }} : {{ item.host }} : {{ current_index }}  "
      when: current_index == item.index
      with_items:
        - "{{ cassandra_restore }}"

我使用以下变量

cassandra_restore:
  - { index: "0", host: 192.168.0.1 }
  - { index: "1", host: 192.168.0.2 }
  - { index: "2", host: 192.168.0.3 }