count.index for dictionary in Ansible
Is it possible to auto generate the vm10,vm11,vm12 in the below script (as count.index used in terraform) ? I would like to pass/define name "vm" and should be able to deploy 3 vm's with the different names vm10, vm11 and vm12. Please suggest a way, Thanks
---
- 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 }}"
Solution 1:
Use an inventory instead of a dict. You want 100 vms?
vms:
hosts:
vm[001:100]:
mem: 1024
vcpu: 1
This will be interpreted as vm001
,vm002
,...,vm099
,vm100
.
Delegate the task to create them to localhost, since they don't exist when the task is run. Afterwards you can run the setup module and run tasks directly on the newly created VMs.
The corresponding playbook would look like this:
---
- 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