组中主机之间的列表中的Distorbute元素(可使用)

问题描述 投票:2回答:3

我自己的懒惰有问题。

我列出了要执行的类似任务。它们仅在名称上有所不同。可以说这是一个文件夹名称。

---
- vars:
   folders:
    - folder1
    - folder2
    - etc
  hosts:
   - host1
   - host2
   - etc

而且我想以某种方式在主机之间分配“文件夹”。例如循环赛。

我想在角色扮演书中有这样的内容:

- name: Create folder
  file: path={{item}} state=directory
  use_next_from: folders

我如何表示“ use_next_from”为ansible?谢谢!

ansible ansible-playbook
3个回答
0
投票

[如果只想在一堆主机上创建一堆文件夹,那么您实际上只需要创建一个常规任务并在所有主机上运行它:

- hosts: all
  tasks:
    - name: create folder
      file: path={{ item }} state=directory
      with_items: folders

如果需要创建嵌套循环以在每个主机上执行更复杂的操作,则可以使用with_nested构造:

vars:
    folders:
        - folder1
        - folder2
    files:
        - file1
        - file2

tasks:
    - name: create folder
      file: path={{ item }} state=directory
      with_items: folders

    - name: create files in each folder
      file: path={{ item[0] }}/{{ item[1] }} state=touch
      with_nested:
        - folders
        - files

如果您想做“循环”风格的事情,那就困难得多了。 Ansible旨在在所有定义的主机上执行所有任务。您可能需要做一些类似的事情:

vars:
    folders:
        - folder1
        - folder2
    files:
        - file1
        - file2
tasks:
    - name: create folder
      file: path={{ item[0] }} state=directory
      when: ansible_inventory_hostname == item[1]
      with_nested:
        - folders
        - hosts

0
投票

您想要循环。 RTM on loops

如果Bruce的帖子没有回答您的问题,那么您可能想要Looping over Parallel Sets of Data


0
投票

自Ansible 2.5起,index_varindex_var指令。然后您可以执行此操作:

loop_control

例如,当要从清单中定位主机组时,可以在--- - vars: folders: - folder1 - folder2 - etc hosts: - host1 - host2 - etc - tasks: - name: Create folder file: path: "{{item}}" state: directory loop: "{{folders}}" loop_control: index_var: index when: inventory_hostname == hosts[index % hosts|length] 语句中将hosts替换为groups.example

© www.soinside.com 2019 - 2024. All rights reserved.