Ansible中如何将index_var变量用作列表索引?
问题解决:Ansible中使用loop_control索引变量关联slurp结果
这个需求完全可以实现,问题出在你当前代码的语法错误上,修正后即可正常使用索引变量,同时还有更健壮的替代方案。
问题原因分析
你在lineinfile任务的line参数中多写了一个多余的双引号,导致Jinja2表达式解析失败,进而my_idx变量无法被正确识别:
# 错误写法:末尾多了一个双引号 line: font.color={{color_files.results[my_idx].content | b64decode}}"
修正后的索引方案
去掉多余的双引号,确保Jinja2表达式语法正确,索引变量my_idx即可正常生效:
- name: Read temp file with color list slurp: src: /etc/{{item.name}}.tmp register: color_files with_items: - { name: 'blue', code: '#346eeb'} - { name: 'red', code: '#eb3434'} - { name: 'black', code: '#000000'} - name: change config files ansible.builtin.lineinfile: path: /etc/{{ item.name }}.properties regexp: '^font.color=' # 修正:去掉末尾多余的双引号,给整个line值加双引号更规范 line: "font.color={{ color_files.results[my_idx].content | b64decode }}" with_items: - { name: 'blue', code: '#346eeb'} - { name: 'red', code: '#eb3434'} - { name: 'black', code: '#000000'} loop_control: index_var: my_idx
更健壮的替代方案(不依赖索引)
依赖索引的方式需要保证两个循环的列表顺序完全一致,一旦列表顺序变更就会出错。推荐使用zip过滤器将初始列表和slurp结果列表直接关联,避免索引依赖:
- name: Read temp file with color list slurp: src: /etc/{{ item.name }}.tmp register: color_files loop: "{{ color_list }}" vars: color_list: - { name: 'blue', code: '#346eeb'} - { name: 'red', code: '#eb3434'} - { name: 'black', code: '#000000'} - name: change config files ansible.builtin.lineinfile: path: /etc/{{ item.0.name }}.properties regexp: '^font.color=' line: "font.color={{ item.1.content | b64decode }}" # 用zip合并初始列表和slurp结果列表,item.0是初始配置项,item.1是对应的slurp结果 loop: "{{ color_list | zip(color_files.results) | list }}" vars: color_list: - { name: 'blue', code: '#346eeb'} - { name: 'red', code: '#eb3434'} - { name: 'black', code: '#000000'}
这种方式将初始列表定义为变量,通过zip确保每个配置项和对应的临时文件结果一一对应,比索引方式更可靠。
内容的提问来源于stack exchange,提问作者Husker
相关产品推荐
相关产品推荐

