简体   繁体   中英

Multiple with_items in an Ansible module block

I want to create multiple logical volumes with a variable file but it return a sintax error found character that cannot start any token , I have tried in different ways but still doesn't work

main.yml

---
- name: playbook for create volume groups
  hosts: localhost
  become: true
  tasks:
    - include_vars: vars.yml
    - name: Create a logical volume 
      lvol:
        vg: vg03
        lv: "{{ item.var1 }}"
        size: "{{ item.var2 }}"
      with_items: 
        - { var1: "{{ var_lv_name }}", var2: "{{ var_lv_size }}" }

vars.yml

var_lv_name:
  - lv05
  - lv06

var_lv_size:
  - 1g
  - 1g

Use with_together . Test it first. For example,

    - debug:
        msg: "Create lv: {{ item.0 }} size: {{ item.1 }}"
      with_together:
        - "{{ var_lv_name }}"
        - "{{ var_lv_size }}"

gives (abridged)

  msg: 'Create lv: lv05 size: 1g'
  msg: 'Create lv: lv06 size: 1g'

Optionally, put the declaration below into the file vars.yml

var_lv: "{{ var_lv_name|zip(var_lv_size) }}"

This creates the list

  var_lv:
    - [lv05, 1g]
    - [lv06, 1g]

Use it in the code. The simplified task below gives the same results

    - debug:
        msg: "Create lv: {{ item.0 }} size: {{ item.1 }}"
      loop: "{{ var_lv }}"

The previous answer it's totally correct but In my humble opinion we should be getting into the new way to do the things with loop and filters .

Here's my answer:

---
- name: playbook for create volume groups
  hosts: localhost
  gather_facts: no
  become: true

  vars_files: vars.yml

  tasks:
    - name: Create a logical volume 
      lvol:
        vg: vg03
        lv: "{{ item[0] }}"
        size: "{{ item[1] }}"
      loop: "{{ var_lv_name | zip(var_lv_size) | list }}"

In this answer you're using the new way to use loops with keyword loop and using filters like zip and turning the result into a list type for iteration in the loop.

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