使用 multi-ter group_vars 的 Ansible 循环 [英] Ansible loop using multi-ter group_vars

查看:25
本文介绍了使用 multi-ter group_vars 的 Ansible 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 group_vars 在 ansible 中动态创建模板,但似乎无法使嵌套循环正常工作.

I'm trying to dynamically create templates in ansible using group_vars but cannot seem to get the nested loop working.

在 group_vars 中,我有

In group_vars, I have

my_environment:
  serv1:
    foo: 2
    bar: 3
    baz: 3
  serv2:
    foo: 1

我正在尝试创建以下结构:

I'm trying to create the following structure:

/serv1/foo1
/serv1/foo2

/serv1/bar1
/serv1/bar2
/serv1/bar3

/serv1/baz1
/serv1/baz2
/serv1/baz3

/serv2/foo1

一旦上面创建,我想把一个模板文件放到每个目录中,这样最终的结果是:

Once the above is created, I want to put a template file into each directory so the final result would be:

/serv1/bar1/template

/serv2/foo1/template

我的剧本:

- debug: msg="{{ ce }}"
  with_list:
    - "{{ item.value }}"
  loop_control:
    loop_var: ce

以上输出:

ok: [localhost] => (item=None) => {
    "ce": {
        "bar": 3,
        "baz": 3,
        "foo": 2
    },
    "msg": {
        "bar": 3,
        "baz": 3,
        "foo": 2
    }
}

问题是,如何使用 foo 的值迭代 2 次来创建结构?每当我使用 include: with_dictinclude: with_list 时,我总是得到上面的列表?我找不到向下遍历的方法...

The question is, how do I use the value of foo to iterate 2 times to create the structure? Whenever I use an include: with_dict or include: with_list I keep on just getting the above list? I can't find a way to traverse down...

推荐答案

最好的方法是编写您自己的查找插件,该插件将从您的输入中形成所需的路径列表.

The best way is to write your own lookup plugin that will form the desired list of paths from your input.

使用标准查找(循环)你可以这样做:
x.yml:

Using standard lookups(loops) you can do it this way:
x.yml:

- hosts: localhost
  vars:
    my_environment:
      serv1:
        foo: 2
        bar: 3
        baz: 3
      serv2:
        foo: 1
  tasks:
    - include: x2.yml
      with_dict: "{{ my_environment }}"
      loop_control:
        loop_var: my_server

x2.yml:

- include: x3.yml
  with_dict: "{{ my_server.value }}"
  loop_control:
    loop_var: my_param

x3.yml:

- debug: var=item
  with_sequence: end={{ my_param.value }} format=/{{ my_server.key }}/{{ my_param.key }}%1d/template

debug 在 x3.yml 你可以替换为 template 并使用 {{ item }} 作为 dest.

debug in x3.yml you can replace with template and use {{ item }} as dest.

这篇关于使用 multi-ter group_vars 的 Ansible 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆