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

如何在循环场景下将Ansible debug的msg输出为统一列表格式

解决方法

你现在单独输出每条结果的原因是给debug模块加了循环,每次迭代都会单独触发一次debug输出。想要得到合并列表,不需要给debug加循环,直接用过滤器批量处理azure_nic.results的内容后整体输出即可。

推荐写法(使用内置过滤器)

如果你的Ansible版本在2.10及以上,可以用prefix过滤器快速拼接前缀:

- name: 输出已创建的VM列表
  debug:
    msg: "{{ azure_nic.results | map(attribute='invocation.module_args.tags.hostname') | map('prefix', 'Created VM - ') | list }}"

低版本Ansible可以换用正则替换实现同样效果,兼容性更好:

- name: 输出已创建的VM列表
  debug:
    msg: "{{ azure_nic.results | map(attribute='invocation.module_args.tags.hostname') | map('regex_replace', '^', 'Created VM - ') | list }}"

可选写法(Jinja2列表推导)

如果更习惯写显式循环逻辑,可以用Jinja2表达式直接生成目标列表:

- name: 输出已创建的VM列表
  debug:
    msg: "{% set output_list = [] %}{% for item in azure_nic.results %}{{ output_list.append('Created VM - ' ~ item.invocation.module_args.tags.hostname) }}{% endfor %}{{ output_list }}"

以上两种写法输出的msg都会是你需要的合并列表格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:45:04