在Vagrant设置中,我使用Ansible来配置虚拟机.
在其中一个Ansible角色中,我有一个复制文件~/bin/夹内部文件的任务:
~/bin/one.sh
~/bin/two.sh
我想创建这些文件的符号链接,以便最终结果如下:
~/bin/one.sh
~/bin/two.sh
~/bin/one (符号链接到~/bin/one.sh)
~/bin/two(符号链接到~/bin/two.sh)
我怎样才能做到这一点?到目前为止,我已经尝试了这个,但它不起作用:
- name: Common tasks =>Create symlinks for utilities
file: src=~/bin/{{ item }} dest=~/bin/ mode=755 state=link
with_fileglob:
- bin/*
Run Code Online (Sandbox Code Playgroud)
我需要在里面加一个带有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/*
Run Code Online (Sandbox Code Playgroud)
从其他有用的过滤器章节:
获取路径或文件名的根和扩展名(2.0版中的新增内容):
Run Code Online (Sandbox Code Playgroud)# 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/*
Run Code Online (Sandbox Code Playgroud)
当然,上面的任务可以根据您之后编辑的任务中指定的条款进行操作,因为fileglob查找在控制计算机上本地运行(并且在您之前用于复制相同文件的任务中,因此这假定为它们存在于本地机器上).
如果要单独运行任务,首先要使用find模块准备目标节点上的文件列表,然后在结果上运行上述循环.