【问题标题】:Ansible - use with_items and with_sequence at the same timeAnsible - 同时使用 with_items 和 with_sequence
【发布时间】:2015-09-17 15:53:54
【问题描述】:

有没有办法让角色成为这样的一部分: 我需要运行 nrpe.cfg 中的命令五次(配置文件中有 5 个命令 - 所以 5 x 5 个命令)?

- name: grep the commands from nagios
  shell: grep -R check_http_ /etc/nagios/nrpe.cfg | cut -d= -f2-
  register: nagios_check
- name: check_before
  shell: (printf $(echo '{{ item }}' | awk -F'country=' '{print $2}' | cut -d'&' -f1); printf ' ';{{ item }} | cut -d ' ' -f-2) >> {{ ansible_env.DATA_LOG }}/eden-{{ dateext.stdout }}
  register: checkedenbefore
  with_items: "{{ nagios_check.stdout_lines }}"
  **with_sequence: count=5**
  ignore_errors: True

【问题讨论】:

标签: loops sequence roles ansible


【解决方案1】:

您可以使用 with_nested。

- name: grep the commands from nagios
  shell: grep -R check_http_ /etc/nagios/nrpe.cfg | cut -d= -f2-
  register: nagios_check

- name: check_before
  shell: (printf $(echo '{{ item.0 }}' | awk -F'country=' '{print $2}' | cut -d'&' -f1); printf ' ';{{ item.0 }} | cut -d ' ' -f-2) >> {{ ansible_env.DATA_LOG }}/eden-{{ dateext.stdout }}
  register: checkedenbefore
  with_nested:
   - "{{ nagios_check.stdout_lines }}"
   - "{{ range(0, 5) }}"
  ignore_errors: True

【讨论】:

    【解决方案2】:

    这目前是不可能的,但随着 Ansible 2.0 的发布应该再次实现。使用 Ansible 2,您可以将 with_itemsinclude 一起使用,因此您将能够将 check_before 任务包含在单独的 yml 文件中,然后将其与 with_items 一起包含。

    类似的东西:

    ma​​in.yml

    - name: grep the commands from nagios
      shell: grep -R check_http_ /etc/nagios/nrpe.cfg | cut -d= -f2-
      register: nagios_check
    - include: check_before.yml
      with_items: "{{ nagios_check.stdout_lines }}"
    

    check_before.yml

    - name: check_before
      shell: (printf $(echo '{{ item }}' | awk -F'country=' '{print $2}' | cut -d'&' -f1); printf ' ';{{ item }} | cut -d ' ' -f-2) >> {{ ansible_env.DATA_LOG }}/eden-{{ dateext.stdout }}
      register: checkedenbefore
      with_sequence: count=5
      ignore_errors: True
    

    我不知道 Ansible 2 何时发布,但您可以使用 devel branch from github 看看它是否符合您的需求。

    【讨论】:

    • 您回答中的主要问题是它不是一个单一的角色。所以基本上没有“干净”的方式来重复具有“with_items”的任务(x 次)?
    • 不确定这意味着什么:这不是一个单一的角色
    • 在您的回答中,您使用了 2 个角色:main.yml 和 check_before.yml 不是一个
    • 那些是文件,不是角色。您可以在角色中拥有任意数量的文件。 include 语句只包含文件。
    • @ady8531 您应该阅读best practices,然后重新考虑如何构建您的角色。
    猜你喜欢
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多