Ansible循环x次

ady*_*531 6 loops roles ansible

我必须做一些基准测试并循环 10 个命令 3 次(运行所有 10x3,而不是第一个 x3 然后第二个 x3 - 所以运行所有 10x3)。我从寄存器变量中的文件中提取的 10 个命令(它不适用于_lines:然后是命令)并执行它们 1,2,3..,10 将输出传输到文件中,回显某些内容,然后再次执行他们...这一切 3 次

这就是我的做法,x3 下面的代码(nagios_check 注册变量中有 10 个命令/行):

... 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 }}
Run Code Online (Sandbox Code Playgroud)

...上面的这部分我已经写了 3 次(全部)并且在更多代码之后

有没有办法让它变得更简单?(它已经是一个角色,我使用这个角色四次 - 不要让我把它限制在较小的角色中,因为它更复杂,我最终会得到一个巨大的剧本,其中包含类似的内容12x“这个角色”,看起来很可怕)

Htt*_*tqm 7

除了现有的答案之外:您可以使用with_sequencen指令,而不是复制粘贴时间块:include

- name: Do things
  include_tasks: subtask.yml
  with_sequence: count=3
Run Code Online (Sandbox Code Playgroud)


Seb*_*ler 3

您可以将要重复的任务放在单独的 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 }}
Run Code Online (Sandbox Code Playgroud)

然后将其包含在您的剧本中 3 次:

---
# Your playbook
... more code above
- include: task-to-repeat.yml
- include: task-to-repeat.yml
- include: task-to-repeat.yml
Run Code Online (Sandbox Code Playgroud)