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

Ansible提取vmware_guest_info返回的虚拟机IP单个值的方法咨询

从vmware_guest_info返回结果中提取IP的方案

你注册的info变量是标准嵌套JSON结构,直接按层级取值即可,目标IP的取值路径为 {{ info.instance.guest.ipAddress }}

1. 验证取值正确性

先添加debug任务确认提取结果符合预期:

- name: 打印提取到的虚拟机IP
  ansible.builtin.debug:
    var: info.instance.guest.ipAddress

执行该任务后会直接输出单独的IP字符串,无多余嵌套结构。

2. 写入hosts文件示例

使用ansible.builtin.lineinfile模块即可完成本地hosts文件的写入/更新操作,配置参考:

- name: 写入虚拟机IP到本地hosts文件
  ansible.builtin.lineinfile:
    path: /etc/hosts
    line: "{{ info.instance.guest.ipAddress }} {{ vm_name }}"
    state: present
    regexp: "^{{ info.instance.guest.ipAddress }}\\s+"
  become: yes
  delegate_to: localhost

上述配置中regexp参数用于匹配已有相同IP的记录,避免重复添加冗余条目。

提示:如果虚拟机未启动、VMware Tools未正常运行,ipAddress字段可能返回空值,执行前建议先确认虚拟机状态正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:27:03