如何在远程系统上使用Ansible模块移动/重命名文件/目录?我不想使用命令/shell任务,也不想将文件从本地系统复制到远程系统。


当前回答

Bruce并没有试图统计目的地以检查是否移动已经在那里的文件;在尝试mv之前,他正在确保要移动的文件实际存在。

如果你像汤姆一样,只在文件不存在的情况下才移动,我认为我们仍然应该将布鲁斯的支票整合到混合中:

- 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

其他回答

你可以通过

使用Ad Hoc命令

ansible all -m command -a" mv /path/to/foo /path/to/bar"

或者你,如果你想用剧本的话

- name: Move File foo to destination bar
  command: mv /path/to/foo /path/to/bar

在Windows上: —name:将旧文件夹移至备份目录 win_command: "cmd.exe /c move /Y {{sourcePath}}{{目的地文件夹路径}}"

要重命名,请使用rename或ren命令

Bruce并没有试图统计目的地以检查是否移动已经在那里的文件;在尝试mv之前,他正在确保要移动的文件实际存在。

如果你像汤姆一样,只在文件不存在的情况下才移动,我认为我们仍然应该将布鲁斯的支票整合到混合中:

- 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

实现这一点的另一种方法是使用带状态的文件:很难。

这是我要做的一个例子:

- 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- x2)。

我知道这是一个多年前的话题,但我感到沮丧,并为自己构建了一个角色,对任意文件列表执行此操作。扩展到你认为合适的范围:

main.yml

- name: created destination directory
  file:
    path: /path/to/directory
    state: directory
    mode: '0750'
- include_tasks: move.yml
  loop:
    - file1
    - file2
    - file3

move.yml

- name: stat the file
  stat:
    path: {{ item }}
  register: my_file

- name: hard link the file into directory
  file:
    src: /original/path/to/{{ item }}
    dest: /path/to/directory/{{ item }}
    state: hard
  when: my_file.stat.exists

- name: Delete the original file
  file:
    path: /original/path/to/{{ item }}
    state: absent
  when: my_file.stat.exists

注意,此处硬链接比复制更可取,因为它固有地保留了所有权和权限(此外,不会为文件的第二个副本消耗更多的磁盘空间)。