如何在同一源下为 folders/files 创建多个符号链接
How to create the multiple symlinks for the folders/files under the same source
我想创建文件夹:temp2,它能够存储其他文件夹:temp1 的 subfolders/files 的所有符号链接。 with_items
可以帮助完成此任务,但它需要列出所有 folder/file 名称,如下所示的脚本:
- 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 下的 subfolders/files,我需要经常更新上面的脚本以保持符号链接更新
有什么方法可以自动检测 temp1 下的所有 files/folder 而不是维护 with_items
列表?
您可以使用 find
module 创建文件列表:
Return a list of files based on specific criteria. Multiple criteria are AND’d together.
您可能需要将 recurse
设置为 false
(默认),因为您假设子文件夹可能存在。
您需要使用 register
声明注册模块的结果:
register: find
在下一步中,您需要从 the results:
迭代 files
列表
with_items: "{{ find.results.files }}"
并参考 path
键的值。你已经知道怎么做了。
您还需要从路径中提取文件名,以便将其附加到目标路径。为此使用 basename
filter。
以下代码在 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 }}"
我想创建文件夹:temp2,它能够存储其他文件夹:temp1 的 subfolders/files 的所有符号链接。 with_items
可以帮助完成此任务,但它需要列出所有 folder/file 名称,如下所示的脚本:
- 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 下的 subfolders/files,我需要经常更新上面的脚本以保持符号链接更新
有什么方法可以自动检测 temp1 下的所有 files/folder 而不是维护 with_items
列表?
您可以使用
find
module 创建文件列表:Return a list of files based on specific criteria. Multiple criteria are AND’d together.
您可能需要将
recurse
设置为false
(默认),因为您假设子文件夹可能存在。您需要使用
register
声明注册模块的结果:register: find
在下一步中,您需要从 the results:
迭代files
列表with_items: "{{ find.results.files }}"
并参考
path
键的值。你已经知道怎么做了。您还需要从路径中提取文件名,以便将其附加到目标路径。为此使用
basename
filter。
以下代码在 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 }}"