0

以下是脚本(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

上面的脚本正在查找 vm 的 ip 地址并尝试使用 ip-address(直接而不是通过 vCenter 服务器)而不是使用 vsphere_guest 模块连接到该 vm。我使用 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
4

2 回答 2

0

我无法重现相同的错误,但我仍然建议将add_host模块与local_action.

 - name: addHosts to a new group
   local_action: add_host name={{ partnerIP.stdout}} groupname=UpdatedHost
于 2016-02-04T06:45:24.283 回答
0

在做了几次愚蠢的尝试后得到了答案:这条线:

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

在名称和 = 符号之间以及 = 符号和“{{vm_ip}}”之间包含空格,这就是它无法正常工作的原因。虽然它看起来非常愚蠢和毫无意义,但它只能这样工作。该行应该是:

add_host: name="{{vm_ip}}" groups=new_group
于 2016-02-04T13:08:56.513 回答