简体   繁体   English

遍历 ansible playbook 中的循环

[英]traversal through the loop in ansible playbook

I am newbie to ansible and trying to write my first playbook.我是 ansible 的新手,正在尝试编写我的第一本剧本。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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