如何在Ansible Playbook中为同组不同主机分配特定变量值生成文件
Ansible 按列表下标奇偶分配任务到不同主机实现方案
实现逻辑
- 先获取当前主机在
myhost组内的索引,要求inventory中myhost组的顺序为[A, B],此时A的索引为0,B的索引为1 - 遍历
var1列表时通过下标判断元素归属:偶数下标(对应第1、3位值test1、test3)分配给A,奇数下标(对应第2、4位值test2、test4)分配给B - 循环生成对应名称和内容的文件
修改后完整Playbook
- hosts: myhost vars: # 若var1已在var/var.yaml中定义为[test1, test2, test3, test4],可删除原lookup定义避免冲突 # var1: "{{ lookup('vars', TEMPLATE).source }}" # 获取当前主机在myhost组内的索引,转成int类型用于数值计算 current_host_idx: "{{ groups.myhost.index(inventory_hostname) | int }}" tasks: - name: load var1 include_vars: dir: "./var" files_matching: "var.yaml" - name: generate assigned files copy: # 直接渲染文件内容,无需单独调用模板 content: "variable={{ item }}" # loop.index从1开始计数,生成file1、file2...符合命名要求 dest: "/tmp/file{{ loop.index }}" # 遍历var1全量列表 loop: "{{ var1 }}" loop_control: # 声明下标变量,从0开始计数 index_var: loop_idx # 过滤规则:仅处理分配给当前主机的元素 when: loop_idx % 2 == current_host_idx
可选:使用独立模板文件
如果要保留原有的单独模板文件,将copy模块替换为template即可,模板文件建议后缀改为.j2明确为Jinja2模板:
- name: generate assigned files with template template: src: "./file.j2" # 模板内容为 variable={{ item }} dest: "/tmp/file{{ loop.index }}" loop: "{{ var1 }}" loop_control: index_var: loop_idx when: loop_idx % 2 == current_host_idx
注意:如果你的inventory中
myhost组的顺序是B在前、A在后,将when条件调整为loop_idx % 2 != current_host_idx即可正常分配。
内容的提问来源于stack exchange,提问作者asking
相关产品推荐
相关产品推荐

