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

如何将Ansible中Jinja2循环输出的Windows更新标题转为可遍历列表

问题解决步骤

1. <built-in method title of AnsibleUnsafeText object>异常修复

你出现这个异常是因为取值时多加了括号:win_updates返回的updates列表中每个条目都有名为title的属性,如果你写为item.title(),Jinja2会将其识别为调用字符串类型内置的title()(首字母大写)方法,而不是取title属性,就会输出方法对象本身的描述。

正确的直接遍历写法如下:

# 假设你调用win_updates时注册的返回变量名为win_updates_result
- name: 直接遍历获取更新标题
  debug:
    msg: "{{ item.title }}"
  with_items: "{{ win_updates_result.updates }}"

2. 换行拼接字符串转可迭代列表

如果你已经通过Jinja2循环得到了换行分隔的标题字符串,可通过split过滤器按换行符切割得到列表,搭配select过滤器过滤空行:

# 假设你的换行拼接字符串变量为update_title_str
- name: 转换为可迭代列表
  set_fact:
    update_title_list: "{{ update_title_str.split('\n') | select() | list }}"

转换完成后就可以直接用with_items/loop遍历update_title_list变量使用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 22:39:01