Ansible to loop x times

大憨熊 提交于 2019-12-01 20:53:35

You can put the tasks you want to repeat in a separate yaml file:

---
# tasks-to-repeat.yml
- 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 }}

and then include it in your playbook 3 times:

---
# Your playbook
... more code above
- include: task-to-repeat.yml
- include: task-to-repeat.yml
- include: task-to-repeat.yml

I believe your best option is to write custom module that will encapsulate all the steps that you trying to achieve. And put all the variables that different from 1 run to another into a single list.

Based on what you describing I can assume you have problems with:

  1. readability
  2. maintance

This will be much cleaner to have a line that would look similar to this:

 - name: Run my nagios checks
   my_custom_nagios_module_1.0: >
     date={{ item.date }}
     varaible_x={{ item.x }}
   with_items:
     - { date: '%Y-%m-%d', x: 'foo' }
     - { date: '%Y-%m-%d', x: 'bar' }
     - { date: '%Y-%m-%d', x: 'baz' }

as opposed to repeat the same set of tasks over and over again.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!