首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >巢式with_filetree与循环

巢式with_filetree与循环
EN

Stack Overflow用户
提问于 2020-07-09 00:14:59
回答 1查看 696关注 0票数 2

如何嵌套with_filetree和循环?

下面是我使用一个块的尝试:

代码语言:javascript
复制
- name: Deploy
  hosts: all
  connection: ssh
  become: true

  vars:
    instances:
      abcd:
        admin_port: 12345
  
  tasks:
    - name: Template cfg
      vars:
        file_path: "{{ item.path }}"
      block:
        - name: Templating config files
          vars:
            instance: "{{ item.value }}"
          template:
            src: "config-templates/{{ file_path }}"
            dest: "{{ install_dir }}/{{ instance.name }}/"
          loop: "{{ instances | dict2items }}"
      with_filetree: "config-templates"
      when: item.state == 'file'

但不可抱怨的是:

ERROR! 'with_filetree' is not a valid attribute for a Block

我肯定漏掉了一些显而易见的东西,但我不知道该怎么做。它似乎不使用with_nested/with_cartesian。

请帮帮忙。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-09 07:12:44

当包含任务中有几个循环时,使用include嵌套循环是唯一可行的解决方案。

同时,在大多数情况下,包括您的场景,您可以将工作减少到一个循环。基本思想是:创建一个包含所有要循环的元素的列表,而不是嵌套循环。在这种情况下,product filter应该完成这项工作。

另一个“技巧”(因为filetree文档中没有真正的例子.)记住通常可以将with_<some_lookup>循环转换为loop: {{ lookup|query('some_lookup', args....) }}

综上所述,下面是一个应该满足您的要求的示例(未经过充分测试):

代码语言:javascript
复制
- name: Templating from filetree and instances
  vars:
    file: "{{ item.0 }}"
    instance: "{{ item.1.value }}"
  template:
    src: "config-templates/{{ file.path }}"
    dest: "{{ install_dir }}/{{ instance.name }}/"
  loop: "{{ lookup('filetree', 'templates/config') | product(instances | dict2items) | list }}"
  when: file.state == 'file'

编辑:不想推到“我的!”解决方案:),但是如果您没有太多的任务,下面是将所有内容保存在同一个文件中的一个可能的场景。

Edit2:实际上您甚至不需要任务,特别是当您的游戏针对多个主机时。更新了一个完整的示例伪剧本。

代码语言:javascript
复制
- name: Deploy
  hosts: all
  connection: ssh
  become: true

  vars:
    my_files: "{{ lookup('filetree', 'templates/config') | selectattr('state', 'eq', 'file') | list }}"
    action1_list: ['some', 'list']
    action2_list: ['other', 'list']
    
  tasks:
    - name: action 1
      debug:
        msg: action1
      vars:
        file: item.0
        action1_item: item.1
      loop: "{{ my_files | product(action1_list) | list }}"

    - name: action 2
      debug:
        msg: action2
      vars:
        file: item.0
        action2_item: item.1
      loop: "{{ my_files | product(action2_list) | list }}"
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62805492

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档