Allow and skip empty loop

465 views
Skip to first unread message

Adrian Sevcenco

unread,
Apr 3, 2024, 5:12:22 AM4/3/24
to Ansible Project

Hi! I would like to have an task that would delete groups
ONLY if the variable have a content ...

so i have an delete_users_groups.yml:
---
delete_groups:

delete_users:

####
and an users_task.yml with

- name: Delete groups on nodes
ansible.builtin.group:
name: "{{ group_del_name }}"
state: absent
loop_control:
loop_var: group_del_name
loop: "{{ delete_groups }}"

and a playbook with:

---
- hosts: "{{ target | default('all') }}"
gather_facts: False
vars_files:
- "{{ playbook_dir }}/../additions/users/user_group_info.yml"
- "{{ playbook_dir }}/../additions/users/delete_users_groups.yml"

tasks:
- include_tasks: tasks/users_task.yml


The error that i receive is:
Invalid data passed to 'loop', it requires a list, got this instead: None. Hint: If you passed a list/dict of just one element, try adding wantlist=True to your lookup invocation or use q/query instead of lookup.

i tried to add wantlist = True and i got
template error while templating string: expected token 'end of print statement', got '='. String: {{ delete_groups, wantlist=True }}

Any idea how can the loop pe skiped if the target of the loop is empty?

Thanks a lot!
Adrian

Chiku

unread,
Apr 3, 2024, 5:20:00 AM4/3/24
to ansible...@googlegroups.com

Writing delete_groups: like that it mean empty string type.

So you need to write like delete_groups: [] as empty list type.

--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/CAOL4_EXP6xjdOsxKmB_%3D3dQa41B3kdRdR%3DLutuJab0wsxr4PJw%40mail.gmail.com.

Vladimir Botka

unread,
Apr 3, 2024, 8:08:31 AM4/3/24
to Adrian Sevcenco, ansible...@googlegroups.com
On Wed, 3 Apr 2024 12:11:34 +0300
Adrian Sevcenco <adria...@gmail.com> wrote:

> delete_groups:
>
> loop: "{{ delete_groups }}"
>
> The error that i receive is:
> Invalid data passed to 'loop', it requires a list, got this instead: None.

Use the filter *default*

loop: "{{ delete_groups | default([], true) }}"

See:
https://jinja.palletsprojects.com/en/3.1.x/templates/#jinja-filters.default

Optionally, use the module *ansible.utils.validate*
See:
https://docs.ansible.com/ansible/latest/collections/ansible/utils/validate_module.html


--
Vladimir Botka
Reply all
Reply to author
Forward
0 new messages