Ansible:为一组主机创建动态增加编号的目录

Ansible:为一组主机创建动态增加编号的目录,ansible,Ansible,例如,我想为一组5台主机创建10个数量递增的目录。 任务结束后,结果应为: Server1 Server2 Server3 Server4 server5 dir01 dir02 dir03 dir04 dir05 dir06 dir07 dir08 dir09 dir10 如果我必须创建更多的目录,服务器之间的轮换将继续 在一组5台主机中运行以下任务时: - name: Creates Project's d

例如,我想为一组5台主机创建10个数量递增的目录。 任务结束后,结果应为:

Server1   Server2   Server3   Server4   server5
 dir01      dir02    dir03     dir04     dir05
 dir06      dir07    dir08     dir09     dir10
如果我必须创建更多的目录,服务器之间的轮换将继续

在一组5台主机中运行以下任务时:

- name: Creates Project's directory in server
  file:
    path: /opt/dir{{item}}
    state: directory
    owner: xxxx
    group: xxxx
    mode: 0775
  with_sequence:
    start=1
    end=10
    format=%02d
结果是:

Server1   Server2   Server3   Server4   Server5
 dir01     dir01     dir01     dir01     dir01
 dir02     dir02     dir02     dir02     dir02
 dir03     dir03     dir03     dir03     dir03
 dir04     dir04     dir04     dir04     dir04
  ……        ……        ……        ……        ……
 dir10     dir10     dir10     dir10     dir10

我找到了一种在目标主机上循环的解决方案:

- hosts: ...
  var:
    - dirsPerHost: 2
  tasks:
    - file:
        path: /opt/dir{{ '%02x' | format(item) }}
        state: directory
        owner: xxxx
        group: xxxx
        mode: 0775
      delegate_to: "{{play_hosts[ ( (item | int) - 1) % ( play_hosts|length|int ) ] }}"
      run_once: yes
      loop: "{{ range(1, ( ( play_hosts|length|int ) * (dirsPerHost|int) ) + 1) | list}}"
这将在应该像示例一样创建的目录上循环,但在每次循环运行时,它都会选择一个不同的目标主机,并按顺序遍历所有目标主机

变量“play_hosts”包含所有当前目标主机。使用“play_hosts[((item | int)-1)],我们根据“item”中当前的数字选择一个主机。然后,我们将循环的当前运行委托给该主机,因此任务只在该主机上执行。使用“run_once”,我们可以使每个循环只执行一次任务。否则,循环的每次运行将在所选主机上执行,执行次数与“play_hosts”中的主机相同

我还使用了“loop”而不是“with_sequence”,因为这是ansible推荐的。您可以在此处阅读更多有关内容:

使用“dirsPerHost”,您可以选择在每个主机上创建的目录数。这也是“delegate_to”中模运算的原因


我希望这对您有用。

您好,谢谢您的回复。我试图测试剧本,但我得到了以下错误:
错误!在可用的查找插件中查找名为“{range(1,((hosts | length | int)*(dirsperhost | int))+1)| list}}”的查找时出现意外故障
您可能需要检查“ansible--version”。我测试的设置的输出:
ansible 2.7.5配置文件=/etc/ansible/ansible.cfg配置的模块搜索路径=[u'/home/sshmgmt/.ansible/plugins/modules',u'/usr/share/ansible/plugins/modules']ansible python模块位置=/usr/lib/python2.7/dist-packages/ansible executable location=/usr/bin/ansible python version=2.7.12(默认值,2017年12月4日14:50:18)[GCC 5.4.0 20160609]
在复制粘贴解决方案时,我也犯了一个错误,“DirsPerHost”变量没有正确大写。您好,我今天已经用Ansible 2.7在测试环境中测试了它,并按照您所说的那样工作。我对循环进行了调试:{range(1,((play|u hosts | length | int)*(dirsPerHost | int))+1){list}”,并注意到所有服务器都知道所有文件。每个节点如何理解应该创建哪一个?明白了!我将不得不调整它为我的项目,这是分配系统,但你的想法是非常有益的。再次感谢你。