使用查找挖掘自动化 Ansible VMware

Automating Ansible VMware with lookup dig

我目前正在尝试通过不必在变量文件中包含 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_guest 剧本时注册了 newvm。

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

当我 运行 使用 -vvvv 时,我可以看到没有附加 IP:

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

更新 3

当我创建一个简单的 playbook 时它可以工作,只是当我将它放入我的常规流程时,下面这个工作:

---
- 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) }}"