Ansible how to skip the loop if the list is empty

Viewed 17074

I'm running Ansible and I try to make this task work. I have defined the default of the variable "docker_registries" to be an empty list: docker_registries: [] I noticed that I will get error when running the ansible playbook if the list is empty. this is the error I get:

fatal: [***.cloudapp.azure.com]: FAILED! => {"msg": "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'm trying to add the condition that if the "docker_registries" is empty the task continues without raising an error. this is the code for this task:

- name: Log into additional docker registries, when required
  command: docker login -u {{item.username}} -p {{item.password}} {{item.server}}
  become: true
  loop: "{{docker_registries}}"

I tried to change the loop to loop: "{{ lookup(docker_registries, {'skip_missing': True})}}" but I get the error

An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'NoneType' object has no attribute 'lower' fatal: [***.cloudapp.azure.com]: FAILED! => {"msg": "Unexpected failure during module execution.", "stdout": ""}

I'm pretty new with this. Can anyone help?

2 Answers

You could use the when statement in combinaison with the iterable Jinja test.
Because, well, if you want to loop over your variable, then it should be iterable.

- name: Log into additional docker registries, when required
  command: docker login -u {{ item.username }} -p {{ item.password }} {{ item.server }}
  become: true
  loop: "{{ docker_registries }}"
  when: docker_registries is iterable

Based on the content of the variable, the when condition could still not do the trick, because the validity of the data passed to the loop will be considered first.

Now this said, you can use a conditional expression in the loop declaration itself to come around this issue:

- name: Log into additional docker registries, when required
  command: docker login -u {{ item.username }} -p {{ item.password }} {{ item.server }}
  become: true
  loop: "{{ docker_registries if docker_registries is iterable else [] }}"

Also mind that a string is an iterable in Python, as they are, simply put, a list of characters.

So you might want to go:

- name: Log into additional docker registries, when required
  command: docker login -u {{ item.username }} -p {{ item.password }} {{ item.server }}
  become: true
  loop: "{{ docker_registries if docker_registries is iterable and docker_registries is not string else [] }}"

Thank you all guys. I had a line in my group_vars file which I had commented out the all docker_registries username and password and all, but I had not comment the docker_registries: line itself. That's why I was given the None instead of the empty list.

Related