无法在ansible的主机文件中动态添加主机

Can not add the host dynamically in the host file in ansible

脚本如下(Ansible版本为2.1.0):

---
- hosts: localhost
  vars_files:
    - createVmVars.yml

  pre_tasks:
    - name: Gathering Vm info.
      vsphere_guest:
        vcenter_hostname: "{{vcenter_hostname}}"
        username: "{{vcenter_username}}"
        password: "{{vcenter_password}}"
        guest: "{{guest_name}}"
        vmware_guest_facts: yes
      register: var

  tasks:
    - name: Setting the VM Ip address in a variable.
      set_fact:
        vm_ip: "{{var.ansible_facts.hw_eth0.ipaddresses[0]}}"

    - name: Adding a new host in inventory file.
      add_host: name = "{{vm_ip}}" groups=new_group

- hosts: new_group
  remote_user: root

  vars_files:
    - createVmVars.yml

  tasks:
    - name: Copying files from local to target VM.
      copy:
        src: "{{item.source}}"
        dest: "{{item.dest}}"
        mode: 0644
      with_items: files_copy

上面的脚本正在查找虚拟机的 IP 地址并尝试使用 IP 地址(直接而不是通过 vCenter 服务器)而不是使用 vsphere_guest 模块连接到该虚拟机。 我使用 add_host 模块在清单文件中动态添加主机。但是我在 add_host 模块之后(不在 add_host 任务中但在它之后)在执行它时收到以下错误:

意外异常:需要字符串或缓冲区

使用 -vvvv 的完整回溯是:

Unexpected Exception: expected string or buffer
the full traceback was:

Traceback (most recent call last):
  File "/home/shasha/devOps/ansible/bin/ansible-playbook", line 85, in <module>
    sys.exit(cli.run())
  File "/home/shasha/devOps/ansible/lib/ansible/cli/playbook.py", line 150, in run
    results = pbex.run()
  File "/home/shasha/devOps/ansible/lib/ansible/executor/playbook_executor.py", line 140, in run
    for batch in self._get_serialized_batches(new_play):
  File "/home/shasha/devOps/ansible/lib/ansible/executor/playbook_executor.py", line 209, in _get_serialized_batches
    all_hosts = self._inventory.get_hosts(play.hosts)
  File "/home/shasha/devOps/ansible/lib/ansible/inventory/__init__.py", line 189, in get_hosts
    hosts = self._evaluate_patterns(patterns)
  File "/home/shasha/devOps/ansible/lib/ansible/inventory/__init__.py", line 292, in _evaluate_patterns
    that = self._match_one_pattern(p)
  File "/home/shasha/devOps/ansible/lib/ansible/inventory/__init__.py", line 345, in _match_one_pattern
    hosts = self._enumerate_matches(expr)
  File "/home/shasha/devOps/ansible/lib/ansible/inventory/__init__.py", line 441, in _enumerate_matches
    matching_hosts = self._match_list(group.get_hosts(), 'name', pattern)
  File "/home/shasha/devOps/ansible/lib/ansible/inventory/__init__.py", line 163, in _match_list
    if pattern.match(getattr(item, item_attr)):
TypeError: expected string or buffer

我无法重现相同的错误,但我仍然建议将 add_host 模块与 local_action 一起使用。

 - name: addHosts to a new group
   local_action: add_host name={{ partnerIP.stdout}} groupname=UpdatedHost

经过几次愚蠢的尝试后得到了答案: 该行:

add_host: name = "{{vm_ip}}" groups=new_group

在名称和 = 符号之间以及 = 符号和“{{vm_ip}}”之间包含空格,这就是它不起作用的原因 properly.Though 它看起来非常愚蠢且毫无意义,但它起作用了only.The 行应该是:

add_host: name="{{vm_ip}}" groups=new_group