Ansible 中字典的 count.index

Ansible 中字典的 count.index

是否可以在下面的腳本中自動產生 vm10、vm11、vm12(如 terraform 中使用的 count.index)?我想傳遞/定義名稱“vm”,並且應該能夠部署 3 個具有不同名稱 vm10、vm11 和 vm12 的虛擬機器。請推薦一個方法,謝謝

---
- hosts: Target                         
  vars:
    machines:                  
      v10:
        mem: 1024
        vcpu: 1
      v11:
        mem: 1024
        vcpu: 1
  tasks:
  - name: img cpy
    copy:
      src: /root/pri.qcow2
      dest: /test/{{ item.key }}.qcow2
      remote_src: yes
    with_dict: "{{ machines }}"
  - name: Import/Load VM
    command: >
             virt-install --name {{ item.key }} --memory {{ item.value.mem }} --vcpus {{ item.value.vcpu }} --disk /test/{{ item.key }}.qcow2,bus=sata --import --os-variant generic --network default --noreboot
    with_dict: "{{ machines }}"

答案1

使用清單而不是字典。您想要 100 個虛擬機器嗎?

vms:
  hosts:
    vm[001:100]:
      mem: 1024
      vcpu: 1

這將被解釋為vm001, vm002,..., vm099, vm100代表將它們建立到本機的任務,因為它們在任務運行時不存在。之後您可以運行設定模組並直接在新建立的虛擬機器上執行任務。

相應的劇本如下所示:

---
- hosts: vms
  gather_facts: no
  tasks:
  - name: copy qcow image to target path
    copy:
      src: /root/ovms/pri.qcow2
      dest: /root/ovms/test/{{ inventory_hostname }}.qcow2
      remote_src: yes
    delegate_to: target
  - name: Import/Load VM
    command: >
            virt-install --name {{ inventory_hostname }} --memory {{ mem }} --vcpus {{ vcpu }} --disk /root/ovms/test/{{ inventory_hostname }}.qcow2,bus=sata --import --os-variant generic --network default --noreboot
    delegate_to: target

相關內容