【问题标题】:Ansible nested loops, how to set inner loop variable based on outer variableAnsible嵌套循环,如何根据外部变量设置内部循环变量
【发布时间】:2018-05-10 19:51:39
【问题描述】:

我在 ansible 上遇到了嵌套循环问题。

我正在使用带有以下配置文件的 ansible 2.5.2:

文件主机

[group1]
host1
host2
host3
[group2]
hostA

文件 host_vars/host{N}(其中 N 是 group1 上每个主机的编号):

variable:
  - { line: "keyB" , file: "keyc"}
  - { line: "key2" , file: "key3"}

我需要为 host_vars/host{N} 中的每一行在 hostA 上执行一项任务。

在伪代码中,需要这样的东西:

- name: modify file
  for host in groups['group1']:
    for item in host['variables']:
      lineinfile: "path={{ host }}/{{ item.file }} line={{ item.line }}"

使用 jinja2 循环不起作用:

- name: Modify files
  lineinfile: "{% for linea in hostvars[item]['variables'] %}
              path={{ item }}/{{ linea.file }}
              line={{ linea.line }}
              {% endfor %}"
  loop: "{{ groups['group1'] }}"

正常的嵌套循环也不起作用,因为内部循环取决于主机名:

- name: Modify files
  lineinfile: "path={{ item[0] }}/{{ item[1]['file'] }} line={{ item[1]['line'] }}"
  with_nested:
  - "{{ groups['group1'] }}"
  - "{{ hostvars[item[0]]['variables'] }}"

还有另一种循环嵌套循环的方法吗?

【问题讨论】:

    标签: ansible jinja2 nested-loops


    【解决方案1】:

    我使用 loop_control 解决了我的问题,

    我添加了一个新文件:inner.yml

    - name: Modify files
      lineinfile: "path={{ outer_item }}/{{ item.file }} line={{ item.line }}"
      loop: "{{ hostvars[outer_item]['variables'] }}"
    

    并将我的任务文件定义如下

    - include_tasks: inner.yml
      loop: "{{ groups['group1'] }}"
      loop_control:
        loop_var: outer_item
    

    这解决了我在循环中使用两个嵌套变量的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-05
      • 1970-01-01
      • 2013-08-19
      • 2013-05-25
      相关资源
      最近更新 更多