Ansible - 通过 vCenter API 为 ESXi 主机创建动态清单

发布于 2025-01-13 09:52:31 字数 1583 浏览 5 评论 0原文

我要求为每个集群创建 ESXi 主机的动态清单,我使用“community.vmware.vmware_cluster_info”并在提取 json 值方面发挥了一些作用,实现了这一点来自剧本中的注册 var。我想与社区分享这一点,以防万一有人手头有类似的任务。

仅供参考 - 有一个 Ansible 模块,适用于 动态清单,但这适用于虚拟机不适用于 ESXi 主机清单。

步骤 1 - 这是从 vCenter 获取集群信息,并将输出存储/注册在“cluster_info”中

- name: Gather info about the cluster 
  community.vmware.vmware_cluster_info:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password)}}"
    cluster_name: "Cluster-Name"
    validate_certs: no
  delegate_to: localhost
  register: cluster_info

步骤 2 - 这是过滤掉 ESXi 主机值并将其作为“事实”存储在cluster_hosts。我们使用寄存器值“cluster_info”(来自步骤 1)和 dict 来过滤出所需的信息。

- name: Generate Dynamic Inventory for Cluster 
  set_fact:
    cluster_hosts: "{{ item.value.hosts | map(attribute='name') | list | sort }}"
  with_dict: "{{ cluster_info.clusters }}"
  loop_control:
    label: '{{ item.key }}'
  tags:
    - dynamic_inventory

步骤 3 - 现在我们使用步骤 2 生成的列表并循环它并创建一个主机组(使用“add_host”模块),其中包含可用于下一个任务/剧本的主机。

- name: Dynamic Inventory Group created
  add_host:
    hostname: "{{ item }}"
    groups: esxi_dynamic_inventory
  loop: "{{ cluster_hosts }}"
  tags:
    - dynamic_inventory

如有任何问题,请随时提出。

I had an ask to create a dynamic inventory of ESXi Hosts for each Cluster and I achieved that using the 'community.vmware.vmware_cluster_info' and doing some magic around extracting json values from register var in a playbook. I thought of sharing this with the community just in case anyone has got a similar task on hand.

FYI - There is an Ansible module for dynamic inventory but that is for VM's and NOT for ESXi Hosts inventory.

Step 1 - This is to get the Cluster info from vCenter and store/register the output in "cluster_info"

- name: Gather info about the cluster 
  community.vmware.vmware_cluster_info:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password)}}"
    cluster_name: "Cluster-Name"
    validate_certs: no
  delegate_to: localhost
  register: cluster_info

Step 2 - This is to filter out the ESXi Hosts value and store it as a 'fact' in cluster_hosts. We are using register value 'cluster_info' (from step 1) with dict to filter out the required info.

- name: Generate Dynamic Inventory for Cluster 
  set_fact:
    cluster_hosts: "{{ item.value.hosts | map(attribute='name') | list | sort }}"
  with_dict: "{{ cluster_info.clusters }}"
  loop_control:
    label: '{{ item.key }}'
  tags:
    - dynamic_inventory

Step 3 - Now we are using the list generated from Step 2 and looping it and creating a Host group (using 'add_host' module) containing those hosts that can be used for next task/playbook.

- name: Dynamic Inventory Group created
  add_host:
    hostname: "{{ item }}"
    groups: esxi_dynamic_inventory
  loop: "{{ cluster_hosts }}"
  tags:
    - dynamic_inventory

Any questions feel free to ask.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蝶舞 2025-01-20 09:52:31

几年前我也遇到过同样的情况。

我所做的就是从 Ansible 获取 vmware 模块之一的源代码,并编写一个返回主机列表的模块。

您可以从 Ansible 获取任何 vmware 模块(例如 https://github.com/ansible-collections/community.vmware/blob/98fb3fe441de096778a0bf4b5ba9c3d146c47f72/plugins/modules/vmware_guest_find.py)并使用以下代码对其进行调整。

它是一个自定义模块,因此您应该将其放置在您正在编写的角色或集合的库目录中的某个位置。

class PyVmomiHelper(PyVmomi):
    def __init__(self,module):
        super(PyVmomiHelper, self).__init__(module)
        cluster = self.params['cluster_name']
        self.host_obj_list = self.get_all_host_objs(cluster_name=cluster)

    def get_host_obj_list(self):
        results = dict(changed=False, result=dict())
        host_list = []
        for host in self.host_obj_list:
            host_list.append(host.name)
        results['result']["host_list"] = host_list
        self.module.exit_json(**results)

def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(dict(
        cluster_name=dict(type='str')
    ))

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=False,
                           required_one_of=[
                               ['cluster_name']
                           ])

    try:
        pyv = PyVmomiHelper(module)
        pyv.get_host_obj_list()
    except vmodl.RuntimeFault as runtime_fault:
        module.fail_json(msg=to_native(runtime_fault.msg))
    except vmodl.MethodFault as method_fault:
        module.fail_json(msg=to_native(method_fault.msg))
    except Exception as e:
        module.fail_json(msg=to_native(e))

I faced the same situation a few years ago.

What I did is take the source code from Ansible for one of the vmware modules and write a module that returned the host list.

You can take any vmware module from Ansible (like https://github.com/ansible-collections/community.vmware/blob/98fb3fe441de096778a0bf4b5ba9c3d146c47f72/plugins/modules/vmware_guest_find.py) and adapt it with the following code.

It is a custom module, so you should place it somewhere in the library directory of the role or collection you are writing.

class PyVmomiHelper(PyVmomi):
    def __init__(self,module):
        super(PyVmomiHelper, self).__init__(module)
        cluster = self.params['cluster_name']
        self.host_obj_list = self.get_all_host_objs(cluster_name=cluster)

    def get_host_obj_list(self):
        results = dict(changed=False, result=dict())
        host_list = []
        for host in self.host_obj_list:
            host_list.append(host.name)
        results['result']["host_list"] = host_list
        self.module.exit_json(**results)

def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(dict(
        cluster_name=dict(type='str')
    ))

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=False,
                           required_one_of=[
                               ['cluster_name']
                           ])

    try:
        pyv = PyVmomiHelper(module)
        pyv.get_host_obj_list()
    except vmodl.RuntimeFault as runtime_fault:
        module.fail_json(msg=to_native(runtime_fault.msg))
    except vmodl.MethodFault as method_fault:
        module.fail_json(msg=to_native(method_fault.msg))
    except Exception as e:
        module.fail_json(msg=to_native(e))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文