Templates 使用查找功能自动化Ansible VMware

Templates 使用查找功能自动化Ansible VMware,templates,ansible,vmware,esxi,Templates,Ansible,Vmware,Esxi,我目前正在尝试通过不必在变量文件中包含IP地址来进一步自动化VM自动化。我在dig中找到了nslookup模块,但我觉得这是一个错误的方法,例如,这里是创建时读取的变量文件,了解详细信息: # VMware Launch Variables # If this is a test deployment you must ensure the vm is terminated after use. vmname: agent5 esxi_datacenter: Datacenter esxi_

我目前正在尝试通过不必在变量文件中包含IP地址来进一步自动化VM自动化。我在dig中找到了nslookup模块,但我觉得这是一个错误的方法,例如,这里是创建时读取的变量文件,了解详细信息:

# VMware Launch Variables

# If this is a test deployment you must ensure the vm is terminated after use.
vmname: agent5

esxi_datacenter: Datacenter
esxi_cluster: Cluster
esxi_datastore: ds1 # Do not change value.
esxi_template: template-v2
esxi_folder: agents # Folder must be pre-created

# Static IP Addresses
esxi_static_ip: "{{ lookup('dig', '{{ vmname }}.example.com.') }}"
esxi_netmask: 255.255.252.0
esxi_gateway: 10.0.0.1
我希望用这些做的只是“esxi_static_ip”,但用dig查找时会立即启动。然而,这在其当前状态下不起作用

发生的情况是VM启动时没有ipv4地址,或者更常见的情况是它失败并出现以下错误:

fatal: [localhost -> localhost]: FAILED! => {"changed": false, "msg": "Failed to create a virtual machine : A specified parameter was not correct: spec.nicSettingMap.adapter.ip.ipAddress"}
我获取IP并将其传递,当我在vmware-lanch-vars.yml文件中硬编码esxi_static_IP:时,它就会起作用。但是,如果我使用(包括示例),它将失败

当我运行vmware\u guest playbook时,会注册新VM

- name: Make virtual machine IP persistant
  set_fact:
    newvm_ip_address: '{{ newvm.instance.ipv4 }}'

- name: Add host to in memory inventory
  add_host:
    hostname: "{{ newvm_ip_address }}"
    groups: just_created
    newvm_ip_address: "{{ newvm.instance.ipv4 }}"
当我使用-VVV运行时,我可以看到没有连接IP:

    "networks": [
        {
            "device_type": "vmxnet3",
            "gateway": "0.0.0.01",
            "ip": "",
            "name": "Network",
            "netmask": "255.255.252.0",
            "type": "static"
        }
    ],
更新3

当我创建一个简单的剧本时,它是有效的,而不是当我将它放入我的常规流程时,下面的工作:

---
- hosts: localhost
  vars:
    vmname: "apim-sb-ng1-agent2"
    vm_dig_fqdn: "{{ vmname }}.example.com."
    esxi_static_ip: "{{ lookup('dig', vm_dig_fqdn) }}"

  tasks:
    - debug: msg="{{ esxi_static_ip }}" 

我不确定这是您面临的第一个问题(请参阅我上面的评论),但您的jinja2模板表达式是错误的

当已经在jinja2表达式扩展中时,不能使用jinja2表达式扩展

在这种情况下,必须使用
+
运算符连接变量和字符串:

esxi_static_ip:“{{lookup('dig',vmname+'.example.com.')}”
如果您喜欢在任何地方使用jinja2扩展,您可以在不同的变量中进行分离,例如:

vm_dig_fqdn:“{{vmname}}}.example.com。”
esxi_static_ip:“{{lookup('dig',vm_dig_fqdn)}”

请给出“不起作用”的准确定义。我对缺少该信息表示歉意。我已经添加了发生的情况,包括使用以下示例。我希望我会,因为所有正在启动的虚拟机都是静态IP,所以这将是最简单的方法。如前所述,如果我在esxi_static_IP中硬编码IP,它会创建在get_facts中找到的“instance.ipv4”,我会传递它。如果我尝试动态,它一定不会。最后,它看起来像是我这边的一个打字错误,这适用于您的第二个示例。非常感谢你。