Reputation: 13491
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?
Upvotes: 3
Views: 1280
Reputation: 68489
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
Upvotes: 4
Reputation: 450
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
Upvotes: 1
Reputation: 446
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")
Upvotes: 0