首页 > 解决方案 > Ansible - 如何在不使用清单文件的情况下使用 IP 地址作为主机?

问题描述

我正在制作一个从模板部署 VM 的剧本,然后收集从 DHCP 获得的新 IP 地址,然后自动更新新 VM。到目前为止,我已经有了一个变量,其中包含要用于更新播放的 IP 地址。我将它作为主机提供:变量名

只有这不起作用,我收到错误:[警告]:无法匹配提供的主机模式,忽略:172.16.0.33。

我四处搜索,发现我应该使用带有别名的主机模式,但我无法正确获取语法,在尝试后我得到了这个错误:

**ERROR! Unexpected Exception, this is probably a bug: unhashable type: 'AnsibleMapping'
the full traceback was:
 
Traceback (most recent call last):
  File "/usr/bin/ansible-playbook", line 123, in <module>
    exit_code = cli.run()
  File "/usr/lib/python3/dist-packages/ansible/cli/playbook.py", line 127, in run
    results = pbex.run()
  File "/usr/lib/python3/dist-packages/ansible/executor/playbook_executor.py", line 116, in run
    all_vars = self._variable_manager.get_vars(play=play)
  File "/usr/lib/python3/dist-packages/ansible/vars/manager.py", line 171, in get_vars
    magic_variables = self._get_magic_variables(
  File "/usr/lib/python3/dist-packages/ansible/vars/manager.py", line 482, in _get_magic_variables
    _hosts_all = [h.name for h in self._inventory.get_hosts(pattern=pattern, ignore_restrictions=True)]
  File "/usr/lib/python3/dist-packages/ansible/inventory/manager.py", line 374, in get_hosts
    if pattern_hash not in self._hosts_patterns_cache:
TypeError: unhashable type: 'AnsibleMapping'**

我遵循与https://docs.ansible.com/ansible/latest/user_guide/intro_patterns.html [模式限制] 和https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html相同的语法#inventory 别名

我的测试代码得到了上述错误。这不是整个剧本,但与问题无关。第一个错误是当我只为主机使用 IP 时:

- name: Update all packages using apt
  hosts:
    host1:
      #This was also tried seperately
      #ansible_port: 5555
      #ansible_host: 172.16.0.33
      host: 172.16.0.33
  become: yes
  remote_user: user01
  tasks:
    - name: Ansible Update Cache and Upgrade all Packages
      register: updatesys
      apt:
              name: "*"
              state: latest
              update_cache: yes

这不是你的做法吗?有人可以详细说明吗?如何只使用 IP 连接到我的主机并执行命令而不制作清单文件?由于剧本的性质,我不能这样做。每次它使用新的名称和 IP 制作新的虚拟机。我无法手动添加/删除它们。

标签: pythonpython-3.xansible

解决方案


实际上,您可以使用 add_host 模块随时随地创建临时清单文件。下面您可以看到我在使用 API 创建虚拟机并将它们添加到清单中以在同一个 playbook 中对它们进行操作时使用的实现。

- name: Create  vm
  hosts: localhost
  tasks:
    - name: An API call to get information about the vm you just created
      uri:
        url: API endpoint
        method: GET
      register: mongo_server

    - name: Add the host to the inventory
      add_host:
        args: "ssh-common-args='-o StrictHostKeyChecking=no'"
        name: "{{mongo_server.name}}"
        groups: "A"
        ansible_ssh_user: "{{mongo_server.user}}"
        ansible_ssh_pass:  "{{mongo_server.pass}}"
        public_ip_addr: "{{mongo_server.ip_addr}}"
        
- name: Connect A and use B's information in it
  hosts: A
  tasks:
    - name: Example task
      debug:
         msg: "randomtext"

推荐阅读