如何在Ansible中从路径各异的多主机获取多个文件?
解决方案
你的核心问题是没有在单台主机内部将fetch_paths和land_paths的对应元素配对遍历,反而错误地遍历了整个主机组。下面是修正后的实现:
修正后的Playbook
--- - name: 从远程主机拉取文件到本地 hosts: hosts tasks: - name: 拉取对应文件 fetch: src: "{{ item.0 }}" dest: "{{ item.1 }}" flat: yes fail_on_missing: yes validate_certs: no # 将fetch_paths和land_paths的对应元素配对,遍历每一对 loop: "{{ fetch_paths | zip(land_paths) | list }}"
关键逻辑说明
- 去掉多余的主机组遍历:Play已经指定
hosts: hosts,任务会自动在每台目标主机上执行,不需要再用with_items: "{{ groups['hosts'] }}"。 - 配对列表元素:用
zip过滤器把fetch_paths和land_paths的对应位置元素打包成元组(比如("path/to/file1", "path/to/file1")),再转成列表供loop遍历。 - 引用配对元素:遍历过程中,
item.0对应当前的远程文件路径,item.1对应本地存放路径,实现一一对应。
可选:优化Inventory写法
如果想让Inventory更易读,可以改用YAML格式的Inventory(比如命名为inventory.yml):
all: hosts: host1: fetch_paths: - "path/to/file1" - "path/to/file2" land_paths: - "path/to/file1" - "path/to/file2" host2: fetch_paths: - "path/to/file1" land_paths: - "path/to/file1" host3: fetch_paths: - "path/to/file1" - "path/to/file2" - "path/to/file3" land_paths: - "path/to/file1" - "path/to/file2" - "path/to/file3"
这样变量结构更清晰,也避免了ini格式中字符串转列表的潜在问题。
内容的提问来源于stack exchange,提问作者Bloke
相关产品推荐
相关产品推荐

