如何在远程系统上使用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

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

其他回答

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

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

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

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

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

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

  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已经存在。

我发现命令模块中的创建选项很有用。这个怎么样:

- name: Move foo to bar
  command: creates="path/to/bar" mv /path/to/foo /path/to/bar

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