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


当前回答

- 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命令,所以它在每个主机上运行一次,移动文件,然后不再运行。

当我需要在几百台主机上移动一个文件或目录时,我会使用这种方法,其中许多主机可能在任何给定时间都处于关机状态。它是幂等的,可以安全地放在剧本里。

其他回答

文件模块不复制远程系统上的文件。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 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: Move foo to bar
  command: creates="path/to/bar" mv /path/to/foo /path/to/bar

我曾经像Bruce P建议的那样使用统计数据进行2个任务方法。现在我用create完成一个任务。我觉得这清楚多了。

- 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
    when: file_data.stat.exists

  - name: report a missing file
    debug: 
      msg: "the file or directory doesn't exist"
    when: not file_data.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)。