Scripts

Welcome to the Nutanix NEXT community. To get started please read our short welcome post. Thanks!

cancel
Showing results for 
Search instead for 
Did you mean: 

Powershell clone from ADSF

SOLVED Go to solution
Wayfarer

Powershell clone from ADSF

Hi,

 

We just got a nutanix cluster and i'm trying to write a script that will migrate a machine from ESXi to AHV using powershell.

I'm at the last piece and i can't get it to work.... i'm stuck at adding disk. I'm trying to do a "Clone from ADSF file" in powershell but i can't figure out. Here's my code:

 

#Get VM id

$vminfo = Get-NTNXVM | where {$_.vmName -eq "server1"}
$vmId = ($vminfo.vmid.split(":"))[2]

 

$diskCloneSpec = New-NTNXObject -Name VMDiskSpecCloneDTO

$diskCloneSpec.imagepath = "/vm-general/server1/server1-flat.vmdk"

$vmDisk = New-NTNXObject -Name VMDiskDTO
$vmDisk.vmDiskClone = $diskCloneSpec

 

 Add-NTNXVMDisk -Vmid $vmId -Disks $vmDisk

 

And i get this error:

 

Add-NTNXVMDisk : The remote server returned an error: (500) Internal Server Error.
At line:1 char:1
+ Add-NTNXVMDisk -Vmid $vmId -Disks $vmDisk
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (Nutanix.Prism.Common.NutanixCluster:Nuta
nixCluster) [Add-NTNXVMDisk], WebException
+ FullyQualifiedErrorId : {"message":"At least one of Image path or VM Disk UUID are
required."},Nutanix.Prism.PS.Cmds.Acropolis.AddVMDisk

 

Any ideas?

 

I will share my script once done.

Thanks

1 ACCEPTED SOLUTION

Accepted Solutions
Highlighted
Nutanix Employee

Re: Powershell clone from ADSF

@AlexR

 

Try below.

 

#Get VM id
$vmuuid = (Get-NTNXVM | where {$_.vmName -eq "server1"}).uuid
$diskCloneSpec = New-NTNXObject -Name VMDiskSpecCloneDTO
$diskCloneSpec.ndfs_filepath = "/vm-general/server1/server1-flat.vmdk"
$vmDisk = New-NTNXObject -Name VMDiskDTO
$vmDisk.vmDiskClone = $diskCloneSpec

Add-NTNXVMDisk -Vmid $vmuuid -Disks $vmDisk

7 REPLIES
Community Manager

Re: Powershell clone from ADSF

Thanks for sharing @AlexR -- I wonder if @Sandeep can get some eyes on it to help out.

Tags (2)
Nutanix Employee

Re: Powershell clone from ADSF

@AlexR Could you please email me and I will see who can assist you further. - Sandeep@Nutanix.com

Nutanix Employee

Re: Powershell clone from ADSF

@AlexR

 

As a workaround, you can add the below "Rest API" call in your script. Will revert shortly with the Powershell code.

 

#=======================Input section=======================

$server = "Cluster_IP"
$username = "username"
$password = "password"
$memoryGB = "integer"
$mem_mb = [int]$memoryGB*1024
$vmname = "vmname"
$vcpu = "integer"
$cores_cpu = "integer"
$desc = "string"
$imgpath = "image_path"
#example
#$imagepath = "/container/filename.ext"

#=======================Main code=======================

$body = "{
""name"": ""$vmname"",
""memoryMb"": ""$mem_mb"",
""numVcpus"": ""$vcpu"",
""numCoresPerVcpu"": ""$cores_cpu"",
""description"": ""$desc"",
""vmDisks"": [
{
""vmDiskClone"": {

""ndfs_filepath"": ""$imgpath""
}

}
]
}"

 

$Uri = "https://${server}:9440/PrismGateway/services/rest/v1/vms/"
$Header = @{
"Authorization" = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($username+":"+$password ))
}

 

#=======================Execution=======================

Invoke-RestMethod -Method POST -Uri $Uri -Headers $Header -Body $body -ContentType application/json

Highlighted
Nutanix Employee

Re: Powershell clone from ADSF

@AlexR

 

Try below.

 

#Get VM id
$vmuuid = (Get-NTNXVM | where {$_.vmName -eq "server1"}).uuid
$diskCloneSpec = New-NTNXObject -Name VMDiskSpecCloneDTO
$diskCloneSpec.ndfs_filepath = "/vm-general/server1/server1-flat.vmdk"
$vmDisk = New-NTNXObject -Name VMDiskDTO
$vmDisk.vmDiskClone = $diskCloneSpec

Add-NTNXVMDisk -Vmid $vmuuid -Disks $vmDisk

Wayfarer

Re: Powershell clone from ADSF

@sandeepmp

 

The API stuff is what I ended doing but i was having problem when adding multiple NICs and HDDs...

The powershell stuff.... WORKS! 

I will share my script once i'm done with it Smiley Happy

 

Thanks a lot!

Wayfarer

Re: Powershell clone from ADSF

Hi all,


Below is the code i use in Powershell to migrate a VM from Vmware to AHV. There's a lot of room for improvement but the hardest part I think is done Smiley Happy

You will need to change some username/password/server IPs for it to work.

Enjoy!

 

 

#Move a VM from Vmware to AHV
#Alexandre Rozand
#05032017

$vcenter = "my_vcenter_server"
$vmware = get-pssnapin | where Name -eq VMware.VimAutomation.Core
If ($vmware -eq $null)
	{
	#Loads vmware CMDlets and connecting to vsphere
	& 'C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1'
	}
If ($globalSmiley Very HappyefaultVIServers -and $globalSmiley Very HappyefaultVIServers.Name -eq $vcenter )
	{
	write-host "Already connected to $globalSmiley Very HappyefaultVIServers.Name" -foregroundColor cyan
	}
else
	{
	write-host "Connecting to Vcenter server $vcenter..." -foregroundColor cyan
	Connect-VIServer -Server $vcenter
	}

#Check if VM exist
Do
	{
	$vmname = read-host "Please enter VM Name"
	$vmexist = Get-VM $vmname -ErrorAction SilentlyContinue
	If (!$vmexist)
		{
		Write-Host "$vmname does not exist, please enter a new one" -foregroundColor red
		}
	}
While (!$vmexist) 

#Check if VM is powered ON. Needs to be On to get the VM's IP.
$vmstate = $vmexist.PowerState
If ($vmstate -eq "PoweredOff")
	{
	Write-host "$vmname is OFF, please turn it ON. Aborting" -foregroundColor red
	break
	}

Write-Host "Getting info on $vmname" -foregroundColor cyan
$vminfo = get-vm $vmname
$vmnetwork = get-networkadapter -vm $vmname
$vmdisks = get-harddisk -vm $vmname

$ramGB = $vminfo.MemoryGB
$ramMB = $ramGB * 1024
$cpucore = (get-view -ViewType virtualmachine | where name -eq $vmname).config.hardware.NumCoresPerSocket
$cpunum = $vminfo.NumCpu
$cpusocket = $vminfo.NumCpu / $cpucore
$vlanname = $vmnetwork.NetworkName
$vlanidinfo = Get-VirtualPortGroup -name $vlanname| Select Name, @{N="VLANId";E={$_.Extensiondata.Config.DefaultPortCOnfig.Vlan.VlanId}}
[int]$vlanid = $vlanidinfo[0].VLANId
$vmip = Get-VM -name $vmname | Select Name, @{N="IPAddress";E={@($_.guest.IPAddress[0])}}

#Connect to nutanix cluster
Write-Host "Connecting to Nutanix cluster $server" -foregroundColor cyan
$server = "my_ntnx_cluster_ip"
$PlainPassword = "my_password"
$username = "admin"
$passwd = $PlainPassword | ConvertTo-SecureString -AsPlainText -Force
Connect-NutanixCluster -Server $server -UserName $username  -password $passwd -AcceptInvalidSSLCerts
if ($?){Write-Host "Failed to bonnect to Nutanix Cluster, aborting" -foregroundColor red
		break
		}

Write-host "Creating VM $vmname..." -ForegroundColor cyan
$taskcreatevm = new-ntnxvirtualmachine -Name $vmname -NumVcpus $cpusocket -NumCoresPerVcpu $cpucore -MemoryMB $ramMB
Do 
	{
	Start-Sleep -Seconds 1
	$myvarTask = (Get-NTNXTask -TaskId $taskcreatevm)
	if ($myvarTask) {Write-host "Waiting for $vmname to be created..." -ForegroundColor Yellow}
	else {Write-host "$vmname created!" -ForegroundColor Green}
	} While ($myvarTask.progressStatus -eq "Running") 

# Get the VmID of the VM
$vminfo = Get-NTNXVM | where {$_.vmName -eq $vmname}
$vmId = ($vminfo.vmid.split(":"))[2]

 
# Set NIC for VM

$ntnxvlanid = Get-NTNXNetwork | where vlanid -eq $vlanid
$nic = New-NTNXObject -Name VMNicSpecDTO
$nic[1].networkUuid = $ntnxvlanid.uuid
$nic[1].requestIp = $true
$nic[1].requestedIpAddress = $vmip.IPAddress
 
# Adding a Nic
$taskaddvmnic = Add-NTNXVMNic -Vmid $vmId -SpecList $nic[1]
Do 
	{
	Start-Sleep -Seconds 1
	$myvarTask = (Get-NTNXTask -TaskId $taskaddvmnic)
	if ($myvarTask) {Write-host "Waiting for NIC to be added..." -ForegroundColor Yellow}
	else {Write-Host "Nic addded" -ForegroundColor Green}
	} While ($myvarTask.progressStatus -eq "Running") 

Write-Host "Shutting down $vmname..." -foregroundColor cyan
Shutdown-VMGuest $vmname -confirm:$false
Do 
	{
	Start-Sleep -Seconds 1
	$myvarTask = (Get-VM $vmname)
	if ($myvarTask) {Write-host "Waiting for $vmname to be shutdown..." -ForegroundColor Yellow}
	else {Write-host "$vmname shutdown!" -ForegroundColor Green}
	} While ($myvarTask.PowerState -eq "PoweredOn") 
	
## Disk Creation

$i= 0
$numberofdisks = $vmdisks.count
Write-Host "$vmname has $numberofdisks disk(s)"
Foreach ($vmdisk in $vmdisks)
	{
	If ($i -ne $numberofdisks)	
		{
		$disksizeMB = $vmdisk.CapacityGB * 1024
		$diskname = ($vmdisk.Filename).Split('/')[-1]
		$diskflat = $diskname -replace ".vmdk", "-flat.vmdk"
		#Creating the disk
		$formattedPath = "/vm-general/$vmname/$diskflat"
		$diskCloneSpec = New-NTNXObject -Name VMDiskSpecCloneDTO
		$diskCloneSpec.ndfs_filepath = "$formattedPath"
		$vmDisk = New-NTNXObject -Name VMDiskDTO
		$vmDisk.vmDiskClone = $diskCloneSpec
		# Adding the Disk to the VM
		Write-Host "Adding disk $i"
		$disktaskuid = Add-NTNXVMDisk -Vmid $vmId -Disks $vmDisk
		Do 
			{
			Start-Sleep -Seconds 1
			$myvarTask = (Get-NTNXTask -TaskId $disktaskuid)
			if ($myvarTask) {Write-host "Waiting for disk $i to be added..." -ForegroundColor Yellow}
			else {Write-Host "Disk $i added!" -ForegroundColor Green}
			} While ($myvarTask.progressStatus -eq "Running")
		$i++
		}
	}

Write-host "Disconnecting from Vcenter..." -foregroundColor cyan
Disconnect-viserver $vcenter -confirm:$false

 

Nutanix Employee

Re: Powershell clone from ADSF

Nice work @AlexR and thanks for sharing.