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


当前回答

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

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

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

其他回答

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

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

- synchronize:
    src: /first/absolute/path
    dest: /second/absolute/path
    archive: yes
  delegate_to: "{{ inventory_hostname }}"
- 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

你可以通过

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

这是我让它为我工作的方式:

  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。在将文件移动到TMP文件夹之前,XTS已经存在。