Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible to loop x times

I have to do some benchmarks and loop over 10 commands 3 times (run all 10x3, not the firstx3 then the secondx3 - so run all 10x3). The 10 commands I extract from a file in a register variable (it doesn't work with_lines: and then the command) and execute them 1,2,3..,10 pipe the output in a file, echo something and then again execute them... all this 3 times

this how I'm doing it the code below x3 (there are 10 commands/lines in the nagios_check registered variable):

... more code above
- name: get the date for naming purpose
  shell: date +%Y%m%d-%HH%MM%SS
  register: dateext
- name: grep the commands from nagios
  shell: grep -R check_http_EDEN_ /etc/nagios/nrpe.cfg | cut -d= -f2-
  register: nagios_check
- name: check_eden_before
  shell: (printf $(echo '{{ item }}' | awk -F'country=' '{print $2}' | cut -d'&' -f1); printf ' ';{{ item }} | cut -d ' ' -f-2) >> {{ ansible_env.DATA_LOG }}/eden-{{ ansible_hostname }}-{{ dateext.stdout }}
  with_items: "{{ nagios_check.stdout_lines }}"
  ignore_errors: True
- name: enter simple line
  shell: echo "=================" >> {{ ansible_env.DATA_LOG }}/eden-{{ ansible_hostname }}-{{ dateext.stdout }}

... this part above I have it written 3 times (all of it) and after more code

is there a way to make it more simpler ?(it's already a role, I use this role 4 times - don't make me brake it in smaller roles because it's more complex and I'll end up with a huge playbook with something like 12x"this role" and it would look horrible)

like image 413
ady8531 Avatar asked Sep 14 '15 05:09

ady8531


People also ask

What is Loop_var in Ansible?

Defining inner and outer variable names with loop_var However, by default Ansible sets the loop variable item for each loop. This means the inner, nested loop will overwrite the value of item from the outer loop. You can specify the name of the variable for each loop using loop_var with loop_control .

How do you use multiple loops in Ansible?

Ansible's syntax also supports the idea of nested looping. Nested loops in many ways are similar in nature to a set of arrays that would be iterated over using the with_nested operator. Nested loops provide us with a succinct way of iterating over multiple lists within a single task.


1 Answers

In addition to existing answers : instead of copy-pasting n times the include block, you can use the with_sequence instruction :

- name: Do things
  include_tasks: subtask.yml
  with_sequence: count=3
like image 149
Httqm Avatar answered Sep 27 '22 22:09

Httqm