【问题标题】:How to switch Ansible playbook to another host when calling second playbook调用第二个剧本时如何将Ansible剧本切换到另一台主机
【发布时间】:2017-12-05 02:06:44
【问题描述】:

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

第一个剧本:

- 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 服务器上运行...

【问题讨论】:

  • 首先,请使用适当的术语:您有一本剧本,一部剧本,并包含一个任务文件。所以你声称你将任务委托给本地主机,但它在其他地方执行?如果是这样,您可以削减您发布的代码的 80% 并获得相同的结果。
  • 此外,&lt;&lt;Get custom facts 任务将针对清单中的所有目标运行多次,但这不是它正在执行的位置。您可能会因误读日志而感到困惑。
  • 当然,以这种方式运行vmware_vm_facts 两次的整个想法似乎很奇怪。

标签: ansible ansible-facts


【解决方案1】:

如果您负担不起为虚拟机设置动态清单的费用,您的剧本应该有两种玩法:一种用于收集虚拟机的 IP,另一种用于在虚拟机上执行任务,如下所示(伪代码):

---
- 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

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

【讨论】:

  • 谢谢,康斯坦丁!我还必须添加 ansible_ssh_user 并通过,b/c 用户显示为“NONE”
猜你喜欢
  • 2018-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-03
  • 1970-01-01
  • 2021-11-09
相关资源
最近更新 更多