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


当前回答

- 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: Move foo to bar
  command: creates="path/to/bar" mv /path/to/foo /path/to/bar

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

你可以通过

使用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

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

从2.0版本开始,在复制模块中可以使用remote_src参数。

如果为True,它将转到src的远程/目标机器。

- name: Copy files from foo to bar
  copy: remote_src=True src=/path/to/foo dest=/path/to/bar

如果你想移动文件,你需要用文件模块删除旧文件

- name: Remove old files foo
  file: path=/path/to/foo state=absent

从2.8版开始复制模块remote_src支持递归复制。

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

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

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