How use with_sequence and with_dict together

334 views
Skip to first unread message

Rafael Tomelin

unread,
Dec 18, 2019, 10:40:46 PM12/18/19
to ansible...@googlegroups.com
Hi,

I want to do loop in the dict variable appliance and in variable have var count.  This count I should like loop count.

appliances:
  fw01:
    count: 2
    vmname: name
    image: redhat
    os_type: Linux
    data_disks:
      - lun: 0
        disk_size_gb: 128
        managed_disk_type: Standard_LRS

I create this task debug for tests:

- name: virtual_machine
  debug:
    msg: "{{ item.key }} - {{ item.value.count }}"
  with_dict:
    - "{{ virtual_machine }}"
  with_sequence: start=0 end="{{ item.value.count }}"

but return this error:
ERROR! duplicate loop in task: sequence



How can create this loop?

--
Atenciosamente,

Rafael Tomelin
Tel.: 51-984104084
Skype: rafael.tomelin

LPI ID: LPI000191271
Red Hat Certified Engineer
Puppet Professional 2017 Certification

Kai Stian Olstad

unread,
Dec 19, 2019, 2:31:19 AM12/19/19
to ansible...@googlegroups.com
On 19.12.2019 04:40, Rafael Tomelin wrote:
> I want to do loop in the dict variable appliance and in variable have
> var
> count. This count I should like loop count.

Matt Martz gave you the answer yesterday when you asked exactly the same
question.


--
Kai Stian Olstad

Vladimir Botka

unread,
Dec 19, 2019, 3:33:58 AM12/19/19
to Rafael Tomelin, ansible...@googlegroups.com
Hi Rafael,

On Thu, 19 Dec 2019 00:40:24 -0300
Rafael Tomelin <rafael....@gmail.com> wrote:

> I want to do loop in the dict variable appliance and in variable have var
> count. This count I should like loop count.
>
> appliances:
> fw01:
> count: 2
> vmname: name
> image: redhat
> os_type: Linux
> data_disks:
> - lun: 0
> disk_size_gb: 128
> managed_disk_type: Standard_LRS
>
> - name: virtual_machine
> debug:
> msg: "{{ item.key }} - {{ item.value.count }}"
> with_dict:
> - "{{ virtual_machine }}"
> with_sequence: start=0 end="{{ item.value.count }}"
>
> but return this error:
> ERROR! duplicate loop in task: sequence
>
> How can create this loop?

It's possible to *include_tasks* and create nested loops. For this purpose
it's necessary to "Define inner and outer variable names with loop_var"
https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html#defining-inner-and-outer-variable-names-with-loop-var

For example the playbook

$ cat playbook.yml
- hosts: master
tasks:
- include_tasks: create-vm.yml
loop: "{{ appliances|dict2items }}"

with this included file

$ cat create-vm.yml
- name: virtual_machine
debug:
msg: "{{ item.key }} - {{ inner_item }}"
with_sequence: start=0 end="{{ item.value.count - 1 }}"
loop_control:
loop_var: inner_item

should give

ok: [master] => (item=0) => {
"msg": "fw01 - 0"
}
ok: [master] => (item=1) => {
"msg": "fw01 - 1"
}

Cheers,

-vlado
Reply all
Reply to author
Forward
0 new messages