Ansible 如何为同一源下的文件夹/文件创建多个符号链接

Ansible 如何为同一源下的文件夹/文件创建多个符号链接,ansible,symlink,Ansible,Symlink,我想创建文件夹:temp2,它能够存储其他文件夹:temp1的子文件夹/文件的所有符号链接with_items可以帮助完成此任务,但它需要列出所有文件夹/文件名,如下脚本所示: - name: "create folder: temp2 to store symlinks" file: path: "/etc/temp2" state: directory - name: "create symlinks & store in temp2" file:

我想创建文件夹:temp2,它能够存储其他文件夹:temp1的子文件夹/文件的所有符号链接
with_items
可以帮助完成此任务,但它需要列出所有文件夹/文件名,如下脚本所示:

- name: "create folder: temp2 to store symlinks"
  file:
    path: "/etc/temp2"
    state: directory

- name: "create symlinks & store in temp2"
  file:
    src: "/etc/temp1/{{ item.src }}"
    dest: "/etc/temp2/{{ item.dest }}"
    state: link
    force: yes
  with_items:
    - { src: 'BEAM', dest: 'BEAM' }
    - { src: 'cfg', dest: 'cfg' }
    - { src: 'Core', dest: 'Core' }
    - { src: 'Data', dest: 'Data' }
这是不灵活的,因为temp1下的子文件夹/文件将被添加或删除,我需要经常更新上面的脚本以保持符号链接的更新

有没有办法自动检测temp1下的所有文件/文件夹,而不是维护带有_items列表的

  • 您可以使用以下方法创建文件列表:

    根据特定条件返回文件列表。将多个条件合并在一起

    您可能需要将
    recurse
    设置为
    false
    (默认值),因为您假定子文件夹可能存在

    您需要使用
    register
    声明注册模块的结果:

    register: find
    
  • 在下一步中,您需要从以下位置迭代
    文件
    列表:

    并参考
    路径
    键的值。你已经知道怎么做了

    您还需要从路径中提取文件名,以便将其附加到目标路径。用这个


  • 以下代码适用于Ansible-2.8:

    - name: Find all files in ~/commands
      find:
        paths: ~/commands
      register: find
    
    - name: Create symlinks to /usr/local/bin
      become: True
      file:
        src: "{{ item.path }}"
        path: "/usr/local/bin/{{ item.path | basename }}"
        state: link
      with_items: "{{ find.files }}"
    

    谢谢TR。我已经按照你的答案做了,而且效果很好!同时,这也是我第一次在堆栈中提出问题。你的回答让人印象深刻&这个平台。再次感谢。附加更新的存档或帮助某人的剧本:-名称:“创建文件夹:temp2以存储符号链接”文件:路径:“/etc/temp2”状态:目录-名称:“递归查找文件”查找:路径:“/etc/temp1”文件类型:“任意”寄存器:查找结果-名称:“创建符号链接并存储在temp2”文件:src:“/etc/temp1/{{item.path | basename}}”dest:“/etc/temp2/{{item.path | basename}”状态:链接强制:yes与{u items:{{find_result.files}”
    - name: Find all files in ~/commands
      find:
        paths: ~/commands
      register: find
    
    - name: Create symlinks to /usr/local/bin
      become: True
      file:
        src: "{{ item.path }}"
        path: "/usr/local/bin/{{ item.path | basename }}"
        state: link
      with_items: "{{ find.files }}"