You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible使用with_sequence循环生成字典列表报错求助

问题根因

  1. with_sequence是Ansible任务级的循环关键字,不允许直接在vars变量定义块中使用,你原先的写法把循环逻辑放在了vars里,不符合Ansible语法规则。
  2. with_sequence的end参数值以模板变量开头,必须用引号包裹,否则YAML解析会抛出语法错误。

解决方案

调整playbook逻辑,通过set_fact任务配合循环生成你需要的字典列表,修正后的完整配置如下:

修正后的task.yml

---
- name: Test dictionaries playbook
  hosts: localhost
  connection: local

  vars:
    mat_cleaner_input_file_path_flow: "/var/opt/miq/sftp/edr-flow"
    mat_cleaner_input_file_path_http: "/var/opt/miq/sftp/edr-http"
    mat_cleaner_input_retention_period: 21600
    # 如果你需要输出到/2就把该值改为2,原配置中的5会输出到/5
    http_range: 2
    # 初始化空列表用来存储生成的配置
    cleaner_config: []

  tasks:
    - name: 生成cleaner配置列表
      set_fact:
        cleaner_config: "{{ cleaner_config + [{'dir': mat_cleaner_input_file_path_flow + '/' + item|string}] }}"
      with_sequence: start=0 end="{{ http_range }}"

    - name: 渲染配置到输出文件
      template:
        src: /home/osboxes/CleanerConfig/cleaner.config.j2
        dest: /home/osboxes/CleanerConfig/output
      delegate_to: localhost

config.j2 无需修改,保持原有内容即可

{{ cleaner_config | to_nice_yaml(indent=2) }}

输出验证

执行playbook后,/home/osboxes/CleanerConfig/output文件内容将符合你的预期:

dir: /var/opt/miq/sftp/edr-flow/0
dir: /var/opt/miq/sftp/edr-flow/1
dir: /var/opt/miq/sftp/edr-flow/2

内容的提问来源于stack exchange,提问作者Arun Suryan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 16:36:03