Create a VM with REST API

I ran into an issue with my homelab where i tried to run some simple restmethods with powershell but offcourse my homelab does not have decent certificates (why should i even bother :)) So i tried to find a workaround and found this simple piece of code:

add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

After reading through all of this information i found the last link here the most usefull. If you want to make a connection to vcenter you need a token and after that setup a session. I did this with the goal of creating a VM in my homelab. First according to Aventis (see resources i used in the bottom of this post) i made a masterkey and saved my encrypted password :

$KeyFile = "C:\Scripts\MasterKey.key"
$PasswordFile = "C:\Scripts\VC-Password.txt"

$Key = New-Object Byte[] 32
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)
$Key | out-file $KeyFile

#Enter your username & Password when prompt and save the password you enter to $passwordfile
(get-credential).Password | ConvertFrom-SecureString -key (get-content $KeyFile) | set-content $PasswordFile

Now we use the masterkey and password file to make a connection and create my vm (igoring the self signed cert in a different way in this script):

$KeyFile = "C:\Scripts\MasterKey.key"
$PasswordFile = "C:\Scripts\VC-Password.txt"

$Password = Get-Content $PasswordFile | ConvertTo-SecureString -Key (Get-Content $KeyFile)
$UserName = "administrator@vsphere.local" 
$credential = New-Object System.Management.Automation.PsCredential($UserName,$Password)

#Generate Auth
$auth = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Credential.UserName+':'+$Credential.GetNetworkCredential().Password))
$head = @{
  'Authorization' = "Basic $auth"
}

#Ignore SelfSign Cert 
if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type)
{
$certCallback = @"
    using System;
    using System.Net;
    using System.Net.Security;
    using System.Security.Cryptography.X509Certificates;
    public class ServerCertificateValidationCallback
    {
        public static void Ignore()
        {
            if(ServicePointManager.ServerCertificateValidationCallback ==null)
            {
                ServicePointManager.ServerCertificateValidationCallback += 
                    delegate
                    (
                        Object obj, 
                        X509Certificate certificate, 
                        X509Chain chain, 
                        SslPolicyErrors errors
                    )
                    {
                        return true;
                    };
            }
        }
    }
"@
    Add-Type $certCallback
 }
[ServerCertificateValidationCallback]::Ignore()

#Connect to VCSA 
$VCSA_IP = "vcenteriphere"
$RestApi = Invoke-WebRequest -Uri https://$VCSA_IP/rest/com/vmware/cis/session -Method Post -Headers $head
$token = (ConvertFrom-Json $RestApi.Content).value
$session = @{'vmware-api-session-id' = $token}

#add json to the header and create the body for the vm
$session.Add("Content-Type", "application/json")
$body = "{`n    `"spec`": {`n        `"guest_OS`": `"VMWARE_PHOTON_64`",`n        `"name`": `"PAUL-TEST1`",`n        `"placement`" : {`n            `"datastore`": `"datastore-57`",`n            `"folder`": `"group-v21`",`n            `"resource_pool`": `"resgroup-53`"`n        }`n    }`n}"

#Create the vm
$response = Invoke-WebRequest https://$VCSA_IP/rest/vcenter/vm -Method POST -Headers $session -Body $body

I hope this helps to understand REST API a bit better when using powershell as your language.

The resources i used to get all this together :

https://developer.vmware.com/apis/vsphere-automation/latest/

https://blogs.vmware.com/code/2017/02/02/getting-started-vsphere-automation-sdk-rest/

Leave a Reply