在ansible中使用循环生成变量时的问题

问题描述 投票:0回答:1

我想做的是生成大量类似的目录树。我想设置一个描述树模式的字典。然后我希望 ansible 生成具有不同索引的多个目录树,从特殊列表生成。

假设这个简单的剧本:

- hosts: [localhost]
  vars:
    instances: [1,2,3,4]
    dirs:
    - path: "/srvs/hosting{{ instance }}/dir1"
    - path: "/srvs/hosting{{ instance }}/dir2"
#   and so on ......

  tasks:
    - debug:
        msg: "{{ item[1].path }}"
      loop: "{{ instances | product(dirs) | list }}"
      vars:
        instance: "{{ item[0] }}"

在“路径”var 中使用 {{ instance }} var 时,出现错误:

致命:[localhost]:失败! => {“msg”:“[{'path':'/srvs/hosting{{实例}}/dir1'},{'path':'/srvs/hosting{{实例}}/dir2'}]: {{ item[0] }}:“item”未定义”}

我期望得到什么:

ok: [localhost] => (item=[1, {'path': '/srvs/hosting1/dir1'}]) => {
    "msg": {
        "path": "/srvs/hosting1/dir1"
    }
}
ok: [localhost] => (item=[1, {'path': '/srvs/hosting1/dir2'}]) => {
    "msg": {
        "path": "/srvs/hosting1/dir2"
    }
}
ok: [localhost] => (item=[2, {'path': '/srvs/hosting2/dir1'}]) => {
    "msg": {
        "path": "/srvs/hosting2/dir1"
    }
}
ok: [localhost] => (item=[2, {'path': '/srvs/hosting2/dir2'}]) => {
    "msg": {
        "path": "/srvs/hosting2/dir2"
    }
}
ok: [localhost] => (item=[3, {'path': '/srvs/hosting3/dir1'}]) => {
    "msg": {
        "path": "/srvs/hosting3/dir1"
    }
}
ok: [localhost] => (item=[3, {'path': '/srvs/hosting3/dir2'}]) => {
    "msg": {
        "path": "/srvs/hosting3/dir2"
    }
}
ok: [localhost] => (item=[4, {'path': '/srvs/hosting4/dir1'}]) => {
    "msg": {
        "path": "/srvs/hosting4/dir1"
    }
}
ok: [localhost] => (item=[4, {'path': '/srvs/hosting4/dir2'}]) => {
    "msg": {
        "path": "/srvs/hosting4/dir2"
    }
}

我错过了什么?

UPD:我通过重新排列 {{ dirs }} 来实现我的目标,而不使用 {{ instance }} 作为路径的一部分。

dirs:
- path: "dir1"
- path: "dir2"
   
tasks:
  - debug:
      msg: "/srvs/hosting{{ instance }}/{{ item[1].path }}"
    loop: "{{ instances | product(dirs) | list }}"
    vars:
      instance: "{{ item[0] }}"
loops variables ansible nested undefined
1个回答
0
投票

我通过重新排列 {{ dirs }} 来实现我的目标,而不使用 {{ instance }} 作为路径的一部分。

dirs:
- path: "dir1"
- path: "dir2"
   
tasks:
  - debug:
      msg: "/srvs/hosting{{ instance }}/{{ item[1].path }}"
    loop: "{{ instances | product(dirs) | list }}"
    vars:
      instance: "{{ item[0] }}"
© www.soinside.com 2019 - 2024. All rights reserved.