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

如何从Ansible YAML主机文件提取服务器名称并解决loop报错?

提取Ansible主机文件中的服务器名称问题

我有一份YAML格式的Ansible主机文件,结构如下:

all:
  children:
    app_servers:
      hosts:
        server1:
        server2:
        ...

想要提取其中所有服务器名称,编写的Ansible代码如下:

---
- hosts: localhost

  tasks:  

    - include_vars:
        file: "~/code/devops/google/ansible/ansible-root/hosts"

    - set_fact:
        dev_hosts: "{{ all.children.app_servers.hosts }}"

    - debug: msg="{{ item }}"
      loop: "{{ dev_hosts }}"

执行时出现错误:

TASK [debug] **************************************************************************************************************************************************************
Wednesday 01 March 2023  17:42:36 +0000 (0:00:00.027)       0:00:01.075 ******* 
fatal: [localhost]: FAILED! => {"msg": "Invalid data passed to 'loop', it requires a list, got this instead: {'server1': None, 'server2': None, ...}. Hint: If you passed a list/dict of just one element, try adding wantlist=True to your lookup invocation or use q/query instead of lookup."}

不清楚如何使用提示中的wantlist=True,仅希望实现从主机文件中提取服务器名称的需求。


解决方法

问题核心是all.children.app_servers.hosts是一个字典(键为服务器名称,值为None),但loop要求传入列表格式的数据,不需要用到wantlist=True,直接提取字典的键即可。

修改后的代码

---
- hosts: localhost

  tasks:  

    - include_vars:
        file: "~/code/devops/google/ansible/ansible-root/hosts"

    - set_fact:
        dev_hosts: "{{ all.children.app_servers.hosts.keys() | list }}"

    - debug: msg="{{ item }}"
      loop: "{{ dev_hosts }}"

代码说明

  • keys()方法会获取字典中所有的服务器名称(即字典的键)
  • 通过| list过滤器将键的集合转换成列表,满足loop对数据格式的要求

简化写法(省略set_fact步骤)

---
- hosts: localhost

  tasks:  

    - include_vars:
        file: "~/code/devops/google/ansible/ansible-root/hosts"

    - debug: msg="{{ item }}"
      loop: "{{ all.children.app_servers.hosts.keys() | list }}"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 16:43:19