本文介绍了调用第二个剧本时如何将 Ansible 剧本切换到另一台主机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个剧本 - 我的第一个剧本在 ESXi 服务器列表上迭代,获取所有虚拟机的列表,然后将该列表传递给第二个剧本,第二个剧本应该在虚拟机的 IP 上迭代.相反,它仍在尝试在最后一个 ESXi 服务器上执行.我必须将主机切换到我当前传递给第二个剧本的那个 VM IP.不知道怎么切换……有人吗?

I have two playbooks - my first playbook iterates on the list of ESXi servers getting list of all VMs, and then passes that list to the second playbook, that should iterates on the IPs of the VMs. Instead it is still trying to execute on the last ESXi server. I have to switch host to that VM IP that I'm currently passing to the second playbook. Don't know how to switch... Anybody?

第一个剧本:

- name: get VM list from ESXi
  hosts: all

  tasks:
  - name: get facts
    vmware_vm_facts:
      hostname: "{{ inventory_hostname }}"
      username: "{{ ansible_ssh_user }}"
      password: "{{ ansible_ssh_pass }}"
    delegate_to: localhost
    register: esx_facts

  - name: Debugging data
    debug:
      msg: "IP of {{ item.key }} is {{ item.value.ip_address }} and is {{ item.value.power_state }}"
    with_dict: "{{ esx_facts.virtual_machines }}"

  - name: Passing data to include file
    include: includeFile.yml ip_address="{{ item.value.ip_address }}"
    with_dict: "{{ esx_facts.virtual_machines }}"

我的第二本剧本:

- name: <<Check the IP received
  debug:
    msg: "Received IP: {{ ip_address }}"

- name: <<Get custom facts
  vmware_vm_facts:
    hostname: "{{ ip_address }}"
    username: root
    password: passw
    validate_certs: False
  delegate_to: localhost
  register: custom_facts

我确实收到了正确的 VM ip_address,但 vmware_vm_facts 仍在尝试在 ESXi 服务器上运行...

I do receive the correct VM's ip_address but vmware_vm_facts is still trying to run on the ESXi server instead...

推荐答案

如果您负担不起为 VM 设置动态清单,那么您的剧本应该有两种玩法:一种用于收集 VM 的 IP,另一种用于该 VM 上的任务,像这样(伪代码):

If you can't afford to setup dynamic inventory for VMs, your playbook should have two plays: one for collecting VMs' IPs and another for tasks on that VMs, like this (pseudocode):

---
- hosts: hypervisors
  gather_facts: no
  connection: local
  tasks:
    - vmware_vm_facts:
        ... params_here ...
      register: vmfacts
    - add_host:
        name: "{{ item.key }}"
        ansible_host: "{{ item.value.ip_address }}"
        group: myvms
      with_dict: "{{ vmfacts.virtual_machines }}"

- hosts: myvms
  tasks:
    - apt:
        name: "*"
        state: latest

在第一个 play 中,我们从每个虚拟机管理程序收集事实并填充内存清单的 myvms 组.在第二个游戏中,我们为 myvms 组中的每个主机运行 apt 模块.

Within the first play we collect facts from each hypervisor and populate myvms group of inmemory inventory. Within second play we run apt module for every host in myvms group.

这篇关于调用第二个剧本时如何将 Ansible 剧本切换到另一台主机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-13 22:37