我必须做一些基准和循环10个命令3次(运行所有10x3,而不是第一x3然后第二x3--所以运行所有10x3)。这10条命令我从一个文件中提取到一个寄存器变量中(它不能用_lines:然后命令),并执行它们1,2,3...,10管输出在一个文件中,回声,然后再次执行它们......所有这些都是3次。
我是这样做的,下面的代码X3(有10条命令行在nagios_check注册变量)。
... 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 }}
...上面这部分我写了3次(全部),然后写了更多的代码。
有没有办法让它更简单呢?(它已经是一个角色,我用这个角色4次--不要让我把它制动在更小的角色中,因为它更复杂,我最终会有一个巨大的剧本,像12x "这个角色",它会看起来很可怕)。
你可以把你想重复的任务放在一个单独的yaml文件中。
---
# 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 }}
然后把它包含在你的playbook中3次。
---
# Your playbook
... more code above
- include: task-to-repeat.yml
- include: task-to-repeat.yml
- include: task-to-repeat.yml
我相信你最好的选择是 编写自定义模块 这将囊括所有你想实现的步骤。并将所有不同的变量放到一个单一的列表中。
根据你的描述,我可以假设你有以下问题。
这样会干净很多,有一行类似这样的字。
- 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' }
而不是一遍又一遍地重复同样的任务。
除了现有的答案之外:不要复制粘贴 n
一倍 include
块,您可以使用 with_sequence 指导:
- name: Do things
include_tasks: subtask.yml
with_sequence: count=3