Ansible- add disk to vm skipping SCSI ID (x:7)
As the virtual SCSI adapter requires a SCSI ID and No 7 is reserved for it, let’s try to handle it writing Ansible’s task.
We will use ‘vmware_guest_disk‘ module to add disk to vm. Because two disk parameters are required: ‘scsi_controler’ and ‘unit_number’, we will try to use Jinja2 filter ‘|int + 1’ to add next available SCSI device Unit Number.
1. First we need to use ‘vmware_guest_disk_facts‘ module to gather disk facts from our vm where we want to add new vdisk:
- name: Gather disk facts from "{{vmName}}"
vmware_guest_disk_facts:
hostname: "{{ vCenterHostname }}"
username: "{{ vCenterUsername }}"
password: "{{ vCenterPassword }}"
validate_certs: false
datacenter: "{{ vCenterDatacenter }}"
name: "{{ vmName }}"
delegate_to: localhost
register: diskOutput
2. Task to list currently used SCSI Controller Bus Number (controller_key):
- name: set fact - controllerFacts
set_fact:
controllerFacts: "{{ diskOutput.guest_disk_facts.values()| map(attribute='controller_key') | list }}"
3. Next step is to sort ‘controller_key‘ by last number in use.
- name: set facts - controllerKey
set_fact:
controllerKey: "{{ controllerFacts | sort | last }}"
4. Set fact for SCSI device Unit Number (unitNumber) – pay attention at ‘int + 1’ at the end of 3rd line:
- name: set fact - unitNumber
set_fact:
unitNumber: "{{ diskOutput.guest_disk_facts.values() |selectattr('controller_key','equalto',(controllerKey | int))|map(attribute='unit_number')| list | sort | last |int +1 }}"
5. And the most important step – skipping controller SCSI ID No 7. Otherwise you will get an error when add vdisk No 8.
- name: Skip SCSI controller No 7
set_fact:
unitNumber: "{{unitNumber |int+1 }}"
when: unitNumber == "7"
6. So when we have a ‘controllerKey‘ and ‘unitNumber‘ defined we can just use both in ‘vmware_guest_disk‘ module to add new disk to our vm:
- name: Add disk to virtual machine
vmware_guest_disk:
hostname: "{{ vCenterHostname }}"
username: "{{ vCenterUsername }}"
password: "{{ vCenterPassword }}"
validate_certs: false
datacenter: "{{ vCenterDatacenter }}"
name: "{{vmName}}"
disk:
- size_gb: '{{sizeGb}}'
type: '{{diskType}}'
state: present
datastore: "{{ datastoreName }}"
scsi_type: '{{scsiType}}'
scsi_controller: "{{controllerKey[3:4]}}"
unit_number: "{{unitNumber}}"
delegate_to: localhost
register: diskFacts
And that’s it.
Next part will cover creation of Windows partition on disk.