如何使用Ansible模块在远程系统上移动/重命名文件/目录?我不想使用命令/shell任务,也不想将文件从本地系统复制到远程系统。
文件模块不会复制远程系统上的文件。src参数仅在创建指向文件的符号链接时由文件模块使用。
如果您想要在远程系统上完全移动/重命名文件,那么最好的方法是使用命令模块来调用相应的命令:
- name: Move foo to bar
command: mv /path/to/foo /path/to/bar
如果你想变得更花哨,那么你可以首先使用stat模块来检查foo是否确实存在:
- name: stat foo
stat: path=/path/to/foo
register: foo_stat
- name: Move foo to bar
command: mv /path/to/foo /path/to/bar
when: foo_stat.stat.exists
我发现命令模块中的创建选项很有用。这样如何:
- name: Move foo to bar
command: creates="path/to/bar" mv /path/to/foo /path/to/bar
我曾经像Bruce P建议的那样,使用stat来做两个任务的方法。现在,我用creates作为一个任务来做这件事。我认为这要清楚得多。
Bruce并没有试图统计目标以检查文件是否已经在那里移动;他在尝试mv之前确保要移动的文件确实存在。
如果你像Tom一样,只想在文件不存在的情况下移动文件,我认为我们仍然应该把Bruce的check整合到这个组合中:
- name: stat foo
stat: path=/path/to/foo
register: foo_stat
- name: Move foo to bar
command: creates="path/to/bar" mv /path/to/foo /path/to/bar
when: foo_stat.stat.exists
这就是我让它为我工作的方式:
Tasks:
- name: checking if the file 1 exists
stat:
path: /path/to/foo abc.xts
register: stat_result
- name: moving file 1
command: mv /path/to/foo abc.xts /tmp
when: stat_result.stat.exists == True
上面的攻略将检查文件abc.xts是否存在,然后再将文件移动到临时文件夹。
实现这一点的另一种方法是结合使用
file
和
state: hard
。
这是我开始工作的一个例子:
- name: Link source file to another destination
file:
src: /path/to/source/file
path: /target/path/of/file
state: hard
虽然只在本地主机(OSX)上测试过,但也应该可以在Linux上运行。对于Windows,我不能说。
请注意,需要绝对路径。否则它不会让我创建链接。此外,您不能跨文件系统,因此使用任何已挂载的介质可能会失败。
硬链接非常类似于移动,如果您随后删除源文件:
- name: Remove old file
file:
path: /path/to/source/file
state: absent
另一个好处是,当你在一出戏的中间时,变化是持久的。因此,如果有人更改源文件,任何更改都会反映在目标文件中。
您可以通过
ls -l
验证指向文件的链接数量。硬链接的数量显示在模式旁边(例如,当文件有2个链接时,rwxr-xr-x 2)。
另一个对我来说效果很好的选择是使用 synchronize module 。然后使用file模块删除原始目录。
下面是文档中的一个示例:
- synchronize:
src: /first/absolute/path
dest: /second/absolute/path
archive: yes
delegate_to: "{{ inventory_hostname }}"
- name: Move the src file to dest
command: mv /path/to/src /path/to/dest
args:
removes: /path/to/src
creates: /path/to/dest
该命令仅在
/path/to/src
存在而
/path/to/dest
不存在的情况下运行
mv
命令,因此它在每个主机上运行一次,移动文件,然后不再运行。
当我需要移动数百台主机上的文件或目录时,我会使用这种方法,其中许多主机在任何给定时间都可能关机。它是幂等的,并且可以安全地留在剧本中。
- name: Example
hosts: localhost
become: yes
tasks:
- name: checking if a file exists
stat:
path: "/projects/challenge/simplefile.txt"
register: file_data
- name: move the file if file exists
copy:
src: /projects/challenge/simplefile.txt
dest: /home/user/test