我编写了 2 个 Ansible playbook 来创建和销毁 ESXi 实例内的虚拟机。
创建任务是:
- name: Clone the template
delegate_to: localhost
community.vmware.vmware_guest:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
cluster: "{{ vcenter_cluster_name }}"
datacenter: "{{ vcenter_datacenter_name }}"
folder: "{{ vcenter_datacenter_folder }}"
datastore: "{{ vcenter_datastore }}"
validate_certs: False
name: "{{ inventory_hostname }}"
template: "{{ vm_template }}"
state: poweredon
wait_for_ip_address: yes
networks:
- name: "DSwitch_Dati-VM Network 869"
ip: "{{ ansible_host }}"
netmask: "{{ vm_netmask }}"
gateway: "{{ vm_gateway }}"
start_connected: yes
删除剧本是:
- name: TMS Cleaner
hosts: all
remote_user: tms
tasks:
- name: Set powerstate of virtual machine to poweroff
delegate_to: localhost
community.vmware.vmware_guest:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: False
name: "{{ inventory_hostname }}"
state: poweredoff
- name: Remove virtual machine from inventory
delegate_to: localhost
community.vmware.vmware_guest:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
folder: "{{ vcenter_datacenter_folder }}"
datastore: "{{ vcenter_datastore }}"
validate_certs: False
name: "{{ inventory_hostname }}"
delete_from_inventory: True
state: absent
创建正确,而删除可以正确停止并删除虚拟机,但不会从数据存储中删除该文件夹。
如何才能完全删除与虚拟机相关的所有文件?
如果您还想从 datastore 中删除文件,您需要删除以下行:
delete_from_inventory: True
此模块的ansible文档说:
从库存中删除:
选项:是否从清单中删除虚拟机或从磁盘中删除。 没有|是的
仅删除该行,文件将从数据存储中删除。
您必须将 delegate_to: localhost 放在任务末尾。重写如下:
name:将虚拟机的powerstate设置为poweroff
社区.vmware.vmware_guest:
主机名:“{{ vcenter_hostname }}”
用户名:“{{ vcenter_username }}”
密码:“{{ vcenter_password }}”
验证证书:错误
名称:“{{ inventory_hostname }}”
状态: 断电
delegate_to:本地主机
名称:从清单中删除虚拟机
社区.vmware.vmware_guest:
主机名:“{{ vcenter_hostname }}”
用户名:“{{ vcenter_username }}”
密码:“{{ vcenter_password }}”
文件夹:“{{ vcenter_datacenter_folder }}”
数据存储:“{{ vcenter_datastore }}”
验证证书:错误
名称:“{{ inventory_hostname }}”
从库存中删除:真
状态:缺席
delegate_to:本地主机