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

Ansible:循环中当section_1无值时如何跳过对应行?

解决方案

要实现当section_1无值时跳过对应行、仅处理section_3/section_4行的需求,可以通过两种方式动态控制Ansible任务的循环条目:

方法一:为循环条目添加执行条件

给每个循环项定义执行条件,仅当条件满足时才生成对应CSV行:

- name: Print Section to CSV File
  ansible.builtin.lineinfile:
    dest: "{{ output_file }}"
    line: "{{ item.line }}"
    create: true
    state: present
  delegate_to: localhost
  loop:
    # 仅当section_1存在且非空时执行此行
    - line: "{{ section_1 }},{{ section_2 }}"
      run_condition: "{{ section_1 is defined and section_1 | trim != '' }}"
    # 始终处理section_3和section_4的行
    - line: "{{ section_3 }},{{ section_4 }}"
      run_condition: true
  # 对每个循环项应用条件判断
  when: item.run_condition | bool

说明

  • 第一个循环项的run_condition会检查section_1是否已定义且不为空(trim用于排除纯空格的无效值),条件不满足时直接跳过该行的处理,避免未定义变量报错。
  • 第二个循环项始终执行,确保section_3/section_4的行一定会被写入CSV。

方法二:动态生成CSV行列表

通过Jinja2模板预先拼接需要的行,过滤掉无效行后再循环处理:

- name: Print Section to CSV File
  ansible.builtin.lineinfile:
    dest: "{{ output_file }}"
    line: "{{ item }}"
    create: true
    state: present
  delegate_to: localhost
  vars:
    # 用Jinja2动态生成有效CSV行
    csv_content: |
      {% if section_1 is defined and section_1 | trim != "" %}
      {{ section_1 }},{{ section_2 }}
      {% endif %}
      {{ section_3 }},{{ section_4 }}
    # 分割内容并过滤空行,得到最终行列表
    csv_lines: "{{ csv_content.split('\n') | reject('equalto', '') | list }}"
  loop: "{{ csv_lines }}"

说明

  • csv_content会根据section_1的状态决定是否生成第一行,不存在或为空时直接跳过。
  • 通过split('\n')和reject('equalto', '')处理,避免Jinja模板换行产生的空行被写入CSV。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 21:15:57