循环遍历Ansible数组的子集

时间:2019-06-19 19:25:17

标签: loops ansible

我正在研究Ansible剧本,以自动在Grafana中部署某些仪表板。我有很多项目要进入每个仪表板,我如何遍历数组,但要以数组中的4个元素为一组?

这是循环

//div[@class='custom-date-picker-dialog-range-to']//input[@class='md-datepicker-input']

但是我想运行以下命令集:

- name: Loop through the topcs to fill in the template with the topic names (replacing the {kafka_topic_placeholder}) and append them to the working file
      shell: sed 's/{kafka_topic_placeholder}/{{ item }}/g' "{{ widget_template_file_path }}" >> "{{ working_file_name }}"
      loop: "{{ kafka_topic_names }}"

在此列表上:

- name: Create the beginning of row
   shell: sed 's/{dashboard_id_placeholder}/{{ dashboard_id }}/g' "{{ dashboard_template_file_part_1 }}" > "{{ final_output_file_name }}"

- name: Add the contents of our working file
   shell: cat "{{ working_file_name }}" >> "{{ final_output_file_name }}"

- name: Add the ending of the row
   shell: sed 's/{overwrite_placeholder}/{{ overwrite_dashboard }}/g' "{{ dashboard_template_file_part_2 }}" >> "{{ final_output_file_name }}"

因此,我希望最终得到尽可能多的行,以使每行包含4个主题。我可以让它在一行中的所有内容上正常工作,但是我不确定如何在循环中停止操作,执行所需的命令,然后从数组中的同一位置继续循环

1 个答案:

答案 0 :(得分:1)

您可以像Shell脚本一样在一个任务中运行所有命令。

- name: Create the beginning of row
  shell: |
    sed 's/{kafka_topic_placeholder}/{{ item }}/g' "{{ widget_template_file_path }}" >> "{{ working_file_name }}"
    sed 's/{dashboard_id_placeholder}/{{ dashboard_id }}/g' "{{ dashboard_template_file_part_1 }}" > "{{ final_output_file_name }}"
    cat "{{ working_file_name }}" >> "{{ final_output_file_name }}"
    sed 's/{overwrite_placeholder}/{{ overwrite_dashboard }}/g' "{{ dashboard_template_file_part_2 }}" >> "{{ final_output_file_name }}"
  loop: "{{ kafka_topic_names }}"