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


当前回答

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

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

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

其他回答

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

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

这看起来有点过分,但是如果你想避免使用命令模块(我就是这样做的,因为它使用的命令不是幂等的),你可以结合使用copy和unarchive。

使用tar来归档您需要的文件。如果你提前想想,这其实是有道理的。您可能希望在给定目录中有一系列文件。创建包含所有文件的目录,并将它们归档到tar文件中。 使用unarchive模块。当你这样做的时候,随着destination:和remote_src:关键字,你可以把你所有的文件复制到一个临时文件夹开始,然后在你想要的地方解包。

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

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

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

另一个对我来说很有效的选项是使用同步模块。然后使用file模块删除原始目录。

下面是文档中的一个例子:

- synchronize:
    src: /first/absolute/path
    dest: /second/absolute/path
    archive: yes
  delegate_to: "{{ inventory_hostname }}"

文件模块不复制远程系统上的文件。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