在 Vagrant 设置中,我使用 Ansible 来配置虚拟机。
在 Ansible 角色之一中,我的任务是复制 ~/bin/
文件夹中的一些文件:
~/bin/one.sh
~/bin/two.sh
我想创建这些文件的符号链接(symbolic link),因此最终结果如下所示:
~/bin/one.sh
~/bin/two.sh
~/bin/one
(符号链接(symbolic link)到~/bin/one.sh
)
~/bin/two
(符号链接(symbolic link)到 ~/bin/two.sh
)
我怎样才能实现这一目标?到目前为止我已经尝试过这个但它不起作用:
- name: Common tasks =>Create symlinks for utilities
file: src=~/bin/{{ item }} dest=~/bin/ mode=755 state=link
with_fileglob:
- bin/*
我需要在 dest=~/bin/
中放置一个正则表达式,它获取文件名(如 one.sh
)并删除扩展名(one .sh
变成 one
),但我不知道该怎么做。
更新
我终于使用了这个任务:
- name: Copy common files to ~/bin
copy: src={{ item }} dest=~/bin/ mode=755
with_fileglob:
- bin/*
- name: Ensure symlinks for utilities exist
file: src=~/bin/{{ item | basename | regex_replace('(\w+(?:\.\w+)*$)', '\1') }} dest=~/bin/{{ item | basename | regex_replace('\.sh','') }} mode=755 state=link
with_fileglob:
- bin/*
最佳答案
来自other useful filters章节:
To get the root and extension of a path or filename (new in version 2.0):
# with path == 'nginx.conf' the return would be ('nginx', '.conf') {{ path | splitext }}
您需要引用列表的第一个元素,因此:
- name: Common tasks => Ensure symlinks for utilities exist
file: src=~/bin/{{ item }} dest=~/bin/{{ (item | splitext)[0] }} mode=755 state=link
with_fileglob:
- bin/*
<小时/>
当然,考虑到您后来编辑的任务中指定的规定,上述任务是有效的,因为 fileglob
查找是在控制计算机上本地运行的(并且在上一个任务中,您用于复制相同的文件,因此假设它们存在于本地计算机上)。
如果您想单独运行该任务,您必须首先使用 find
module 准备目标节点上的文件列表。然后对结果运行上面的循环。
关于Ansible 角色 : change file extension,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41851418/