Automating vSphere datastore migration with Ansible

Automating virtual machine migration between datastores with Ansible gives infrastructure teams a repeatable way to move workloads without clicking through the vCenter interface. The playbook should orchestrate vSphere’s own migration engine, not copy disks independently, so Storage vMotion entitlements, host placement and datastore compatibility remain under platform control.

A sound workflow begins with declarative inventory and preflight checks, records the intended source and destination, and calls the vCenter API only after those checks pass. The pattern below assumes vCenter 7.x or 8.x, stable VM and datastore identifiers, a trusted certificate path, and explicit failure handling around long-running migration tasks.

Define a safe datastore migration

Begin with a migration contract for each workload. Record its VM identifier, current datastore, destination, power state, service owner and maintenance window. Verify that every destination datastore is visible to the computing cluster and that the source and destination support the required disk formats and access mode.

Confirm the required vCenter and Storage vMotion entitlements before the run. Test snapshots, thin and eagerly provisioned disks, encryption keys, independent media, RDMs and vSAN policy compatibility where applicable. A migration can fail late when a disk, key or policy is unavailable at the destination.

Order workloads by dependency rather than inventory name. Databases may depend on DNS, identity or application services, while shared test estates can move in parallel. Retain a recoverable copy or export where policy requires, and define how traffic, backups and monitoring will be validated during cutover.

Model vCenter objects in Ansible

Represent vCenter as an Ansible inventory group and describe each move as data rather than as a sequence of interface actions. Stable API identifiers are safer than display names, which can be duplicated or changed by an operator. A compact inventory can look like this:

vmware_migrations:
  hosts:
    vcenter:
      ansible_host: vcenter.example.au
  vars:
    vcenter_url: https://vcenter.example.au
    vm_targets:
      vm-1042:
        source: datastore-118
        target: datastore-201
      vm-1088:
        source: datastore-118
        target: datastore-201

Keep the VM identifier and both datastore IDs in every mapping. Store usernames, passwords and CA bundles in Ansible Vault or an external secret provider rather than committed group_vars files. Treat certificates, rollback decisions and test evidence as operational assets, and read the site disclaimer before reusing examples in production.

Build an idempotent migration workflow

The first playbook task uses ansible.builtin.uri to create a short-lived vCenter API session. Restrict the service account to the required migration privileges and datastores, then use the returned session token for subsequent requests:

- name: Create a vCenter API session
  ansible.builtin.uri:
    url: "{{ vcenter_url }}/rest/com/vmware/cis/session"
    method: POST
    url_username: "{{ vcenter_username }}"
    url_password: "{{ vcenter_password }}"
    force_basic_auth: true
    validate_certs: true
  register: vcenter_session
  changed_when: false
  no_log: true

Before submitting a move, query the VM record and its datastore-association endpoint. Return success without action when the VM already occupies the intended datastore. Otherwise, abort on an unexpected source, incompatible power state or inaccessible target. This comparison makes reruns safe after a partial or completed batch.

Submit POST /api/vcenter/vm/{vm}/migrate with the target datastore ID, then poll the returned task through /api/vcenter/tasks/{task} until it reaches a terminal state. Do not blindly retry a POST after a timeout: first check the task identifier and current placement to avoid issuing a duplicate operation. Put the orchestration in a custom collection when strict check-mode support, unit tests or reusable action-plugin behaviour are required.

Fit the workflow into Australian operations

Australian deployments add practical constraints that the code must respect. Sydney and Melbourne data-centre estates often support latency-sensitive workloads and cross-region recovery, so keep storage moves inside the approved jurisdiction and avoid moving replicas or backup catalogues across Australian sites without a separate resilience plan.

Many Australian VMware customers are also working through Broadcom’s subscription and support model. Validate current vCenter, Storage vMotion and support entitlements with the organisation’s licensing contact instead of carrying assumptions from an older perpetual-licence environment into an automated change.

Local peers can provide useful review through VMUG ANZ, especially when a migration pattern is being introduced into a new Australian site. For selected systems, the PowerCLI export workflow can also create supporting evidence, although an export should not substitute for testing the live migration path.

Make the automation repeatable

Make every batch observable. Record the VM ID, source, target, API task ID, operator, timestamp and final placement in structured logs, then link those records to the change ticket. Ansible’s diff output should highlight preflight failures, while vaulted secrets must remain masked in callback output.

Use conservative concurrency for production. Datastore saturation can slow guest I/O even when the API remains responsive, so limit parallel requests per datastore and pace batches around peak business hours. Store the inventory and playbook in Git, review changes as code, and rehearse the complete flow on a disposable VM before assigning production workloads.


Run a controlled pilot now: choose one non-critical VM, keep its credentials in Ansible Vault, execute the read-only preflight in check mode, then perform one migration and attach the vCenter task record to the change ticket. This auditable sequence gives your team a repeatable starting point for safer storage operations across Australian infrastructure.