3

I'd like to stop Nginx just once if any of the items in a list are True.

Because multiple items in the list could be True, I only want to stop Nginx on the first and then not run this command again.

At a later point in the script I will use the same logic to start Nginx again.

- name: Nginx is temporarily shutting down
  command: sudo systemctl stop nginx.service
  when:
    - item == True
  with_items: "{{ saved_results_list }}"

Is there a way to only run this if an item in the list is True, but not multiple times?

Kyslik
  • 8,217
  • 5
  • 54
  • 87
tim_xyz
  • 11,573
  • 17
  • 52
  • 97

3 Answers3

4

You don't need to loop here, it's enough to use the in operator:

- name: Nginx is temporarily shutting down
  command: sudo systemctl stop nginx.service
  when: True in saved_results_list
techraf
  • 64,883
  • 27
  • 193
  • 198
1

If it has little cost to get all items a once you can use the any function.

if any(items):
    stop_nginx()

If not you can use break to stop iteration.

for i in get_data(): 
    if i:
         stop_nginx()
         break

If you have many condition use a flag like this:

nginx_stopped = False
for i in get_data():
    if not nginx_stopped and should_stop_ngingx(i):
         stop_nginx()
         nginx_stopped = True

   #other_conditional branchings
cgte
  • 440
  • 4
  • 10
0

If you have a list like booleans = [True, False, True, False, False], you can use special python functions any() and all() to test whether any or all of the elements in the list are True.

> any(booleans)
> True
>
> all(booleans)
> False

You can use this to shut down Nginx like:

import os

if any(saved_results_list):
    os.system("sudo systemctl stop nginx.service")
Chirag
  • 446
  • 2
  • 14