How do I apply an Ansible with_items loop to the included tasks?

后端 未结 2 1766
独厮守ぢ
独厮守ぢ 2021-01-11 16:56

The documentation for import_tasks mentions

Any loops, conditionals and most other keywords will be applied to the included tasks, not to this statem

相关标签:
2条回答
  • 2021-01-11 17:33

    It is not possible. include/import statements operate with task files as a whole.

    So with loops you'll have:

    Task 1 with Item 1
    Task 2 with Item 1
    Task 3 with Item 1
    Task 1 with Item 2
    Task 2 with Item 2
    Task 3 with Item 2
    Task 1 with Item 3
    Task 2 with Item 3
    Task 3 with Item 3
    
    0 讨论(0)
  • 2021-01-11 17:40

    You can add a with_items loop taking a list to every task in the imported file, and call import_tasks with a variable which you pass to the inner with_items loop. This moves the handling of the loops to the imported file, and requires duplication of the loop on all tasks.


    Given your example, this would change the files to:

    playbook.yml

    ---
    
    - hosts: 192.168.33.100
      gather_facts: no
      tasks:
      - import_tasks: msg.yml
        vars:
          messages:
            - 1
            - 2
    

    msg.yml

    ---
    
    - name: Message 1
      debug:
        msg: "Message 1: {{ item }}"
      with_items:
        - "{{ messages }}"
    
    - name: Message 2
      debug:
        msg: "Message 2: {{ item }}"
      with_items:
        - "{{ messages }}"
    
    0 讨论(0)
提交回复
热议问题