如何解决Ansible 复制文件并从两个列表中获取文件的源和目标名称
我必须复制和重命名多个文件
我将源文件名和目标文件名列表存储在两个列表中:
这里是 sources_files 列表:
sources_files:
- /path1/sourceFileOne.txt
- /path2/sourceFileTwo.txt
...
- /pathN/fileN.txt
这里是 destination_files 列表:
destination_files:
- /path1/destFileOne.txt
- /path2/destFileTwo.txt
...
- /pathN/destfileN.txt
现在我希望我的复制任务从源文件复制到目标文件
/path1/destFileOne.txt
-> /path1/sourceFileOne.txt
我试过用“with_nested”循环
- name: Rename or copy sources files to new names and paths
copy:
remote_src: True
src: "{{ item[0] }}"
dest: "{{ item[1] }}"
when:
- ansible_host in groups[SERVER]
with_nested:
- "{{sources_files}}"
- "{{destination_files}}"
但这似乎无法正常工作,因为该副本最终总是最后一个 dest 文件的内容
建议?
解决方法
您可能需要的数据结构方式 with_together
或 zip
过滤器。
- name: Rename or copy sources files to new names and paths
copy:
remote_src: True
src: "{{ item[0] }}"
dest: "{{ item[1] }}"
when:
- ansible_host in groups[SERVER]
loop: "{{ sources_files|zip(destination_files) }}"
话虽如此,我想知道与其保持两个独立的 列出将它们组合起来更有意义,例如:
copy_files:
- src: /src/file1
dst: /dst/file1
- src: /src/file2
dst: /dst/file2
这使得您的两个列表不太可能最终不同步。
鉴于该数据结构,您的任务将如下所示:
- name: Rename or copy sources files to new names and paths
copy:
remote_src: True
src: "{{ item.src }}"
dest: "{{ item.dst }}"
when:
- ansible_host in groups[SERVER]
loop: "{{ copy_files }}"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。