如何通过Ansible获取VMware主机运行时间(无需连接主机)
解决方法:用
vmware_host_facts模块获取ESXi主机运行时间 嗨,我来帮你搞定这个问题!你之前踩的坑其实是用错了模块:
vmware_vm_facts是专门用来收集虚拟机信息的,所以根本不会返回ESXi主机的运行时间;vmware_host_module是用来管理ESXi主机状态的(比如切换维护模式、开关机),不是用来收集主机事实数据的工具。
正确的模块是vmware_host_facts,它专门从vCenter或者直接从ESXi主机获取主机的详细运行信息,其中就包含我们需要的启动时间(通过它可以计算出运行时长)。
具体操作步骤
首先确保你已经安装了依赖库pyVmomi:
pip install pyVmomi
然后编写Playbook:
- name: 获取ESXi主机运行时间 hosts: localhost gather_facts: yes # 需要收集本地时间来计算运行时长 vars: vcenter_addr: "你的vCenter服务器地址" vcenter_user: "vCenter管理员账号" vcenter_pass: "vCenter管理员密码" target_esxi: "要查询的ESXi主机名/IP" tasks: - name: 收集ESXi主机的事实数据 vmware_host_facts: hostname: "{{ vcenter_addr }}" username: "{{ vcenter_user }}" password: "{{ vcenter_pass }}" validate_certs: no # 如果vCenter用的是自签名证书,需要加这个参数 host_name: "{{ target_esxi }}" register: esxi_facts - name: 直接输出主机启动时间 debug: msg: "{{ target_esxi }} 的启动时间是: {{ esxi_facts.host_facts.runtime.boot_time }}" - name: 计算并输出主机运行时长 debug: msg: "{{ target_esxi }} 已运行: {{ (ansible_date_time.epoch | int - esxi_facts.host_facts.runtime.boot_time.strftime('%s') | int) | timestamp_custom('%d天 %H小时 %M分钟') }}"
关键说明
- 如果不需要通过vCenter,直接连接ESXi主机也是可以的:把
vcenter_addr换成ESXi的地址,账号密码用ESXi的管理员凭据即可。 runtime.boot_time返回的是Python datetime对象,我们可以用strftime('%s')转成时间戳,再和本地当前时间戳计算差值,最后用timestamp_custom格式化成易读的时长。
内容的提问来源于stack exchange,提问作者user7171052
相关产品推荐
相关产品推荐

