简体   繁体   中英

traversal through the loop in ansible playbook

I am newbie to ansible and trying to write my first playbook.

- name: create volume
  volume:
    state: present
    username: "{{ username }}"
    password: "{{ password }}"
    hostname: "{{ inventory_hostname }}"
    vserver: "{{item[0]}}"
    name:  "{{item[1]}}"
    aggregate_name: "{{output}}"
  with_nested:
    - [ 'vs10' , 'vs11' ]
    - [ 'vol1' , 'vol2', 'vol3' , 'vol4' ,'vol5', ''vol6']
  connection: local

Actual output:

vs10-vol1 vol2 vol3 vol4
vs11- vol1 vol2 vol3 vol4

Expected output:

vs10-vol1, vol3 vol5
vs11-vol2, vol4 vol6

This would probably work. I'm basically looping the task against volumes and calculating the vserver in the task.

- name: create volume
  volume:
    state: present
    username: "{{ username }}"
    password: "{{ password }}"
    hostname: "{{ inventory_hostname }}"
    # Calculate which vserver to use based on 'current volume index in the volumes list' and 'length of vservers list'. 
    # The logic uses modulus to try and distribute volumes across given vcenters
    vserver: "{{vservers[(current_index % (vservers|length))]}}"
    # Name is item itself because you are looping volumes
    name:  "{{item}}"
    aggregate_name: "{{output}}"
  # Loop the volumes
  loop: [ 'vol1' , 'vol2', 'vol3' , 'vol4' ,'vol5', 'vol6']
  # This is make a loop_control variable available. This will give us 'current_index'
  loop_control:
    index_var: current_index
  # Vservers are defined here
  vars:
    vservers: [ 'vs10' , 'vs11' ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM