英文:
How can I copy files using the ansible.builtin.copy module and avoid conflicting file names?
问题
我想要将 src
目录中的文件复制到 dest
目录,但不希望同名文件被复制。有谁知道我该怎么做?
- name: 复制文件,但不复制同名文件
copy:
src: <src_dir>
dest: <dest_dir>
英文:
I want files in the src
directory to copy to the dest
directory but I don't want the files with the same name to copy over. Does anyone know how I can do that?
- name: Copy files but not the ones that have the same name
copy:
src: <src_dir>
dest: <dest_dir>
答案1
得分: 3
使用copy
模块的backup
选项。
- copy:
src: foo
dest: /tmp/bar
backup: true
这将创建多个文件,其中,名称与dest
参数指定的文件将代表Ansible的最后一次运行。
例如:
$ ls -l /tmp/
total 12
-rw-r--r-- 1 root root 150 Mar 20 16:30 bar
-rw-r--r-- 1 root root 127 Mar 20 16:20 bar.249.2023-03-20@16:20:44~
-rw-r--r-- 1 root root 148 Mar 20 16:20 bar.329.2023-03-20@16:30:17~
英文:
Use the backup
option of the copy
module.
- copy:
src: foo
dest: /tmp/bar
backup: true
This will create multiple files, of which, the one with the name specified in dest
parameters will be the one representing the last run of Ansible.
For example:
$ ls -l /tmp/
total 12
-rw-r--r-- 1 root root 150 Mar 20 16:30 bar
-rw-r--r-- 1 root root 127 Mar 20 16:20 bar.249.2023-03-20@16:20:44~
-rw-r--r-- 1 root root 148 Mar 20 16:20 bar.329.2023-03-20@16:30:17~
答案2
得分: 3
A: 将参数force设置为false。引用
如果为false,只有在目标不存在时才会传输文件。
- copy:
src: /tmp/test/src/
dest: /tmp/test/dest/
force: false
示例。
给定以下文件
shell> tree /tmp/test/
/tmp/test/
├── dest
│   └── a
└── src
├── a
├── b
└── c
2 directories, 4 files
shell> cat /tmp/test/src/*
src
src
src
shell> cat /tmp/test/dest/*
dest
下面的playbook
- hosts: localhost
tasks:
- copy:
src: /tmp/test/src/
dest: /tmp/test/dest/
force: false
将只复制文件b和c,因为文件a已存在。
shell> tree /tmp/test/
/tmp/test/
├── dest
│   ├── a
│   ├── b
│   └── c
└── src
├── a
├── b
└── c
2 directories, 6 files
shell> cat /tmp/test/dest/*
dest
src
src
英文:
Q: "Don't copy the files with the same name."
A: Set the parameter force to false. Quoting
> If false, the file will only be transferred if the destination does not exist.
- copy:
src: /tmp/test/src/
dest: /tmp/test/dest/
force: false
<hr>
<sup>
Example.
Given the files
shell> tree /tmp/test/
/tmp/test/
├── dest
│   └── a
└── src
├── a
├── b
└── c
2 directories, 4 files
shell> cat /tmp/test/src/*
src
src
src
shell> cat /tmp/test/dest/*
dest
The playbook
- hosts: localhost
tasks:
- copy:
src: /tmp/test/src/
dest: /tmp/test/dest/
force: false
will copy the files b and c only because the file a exists
shell> tree /tmp/test/
/tmp/test/
├── dest
│   ├── a
│   ├── b
│   └── c
└── src
├── a
├── b
└── c
2 directories, 6 files
shell> cat /tmp/test/dest/*
dest
src
src
</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论