如何通过group_var字典批量复制Ansible模板文件至目标主机?
问题分析与解决
问题根源
你的app.yml存在重复键值覆盖问题。YAML字典中相同键(如重复的src/dst)会被最后一次定义的值覆盖,所以system1和system2实际仅保留了最后一组src: 'template/file2.j2'和dst: '/app/user/file2',这就是只复制一个文件的原因。
修复方案
1. 修正app.yml结构
将每个系统的文件配置改为列表格式,才能容纳多个文件条目:
system1: - src: 'template/file1.j2' dst: '/app/user/file1' - src: 'template/file2.j2' dst: '/app/user/file2' system2: - src: 'template/file1.j2' dst: '/app/user/file1' - src: 'template/file2.j2' dst: '/app/user/file2'
2. 优化Playbook(main.yml)
去掉硬编码的system1,改用动态变量引用适配不同系统,同时修正when条件的语法(Ansible中比较需用==):
- name: 复制多个模板文件到目标路径 template: src: "{{ item.src }}" dest: "{{ item.dst }}" when: hostgroup == user_input with_items: "{{ lookup('vars', system_name) }}"
通过lookup('vars', system_name),可以根据传入的system_name变量(如system1或system2)自动匹配对应的文件列表。
3. 运行Playbook时传入变量
执行时通过-e参数指定系统名称和主机组:
ansible-playbook -i inventory main.yml -e "system_name=system1 hostgroup=user_input"
关键提示
- YAML字典不允许重复键,多条目必须用列表存储;
- Ansible中变量比较用
==,=是赋值操作; - 动态变量引用能让Playbook适配多系统场景,避免硬编码。
内容的提问来源于stack exchange,提问作者test1 1
相关产品推荐
相关产品推荐

