PowerCLI

 View Only
Expand all | Collapse all

invoke-restmethod to use vsphere rest apis

LucD

LucDJun 20, 2019 11:11 AM

  • 1.  invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 05:44 AM

    Hi Luc ,

    can you please provide the simple code to get get windows vm in a cluster using rest api available from swagger 6.5 .

    also does this kind of approach needs different kind of authentication to vcenter .



  • 2.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 06:44 AM

    Using the REST API is a bit getting used to.
    Once you get the hang, it becomes easy.

    In this case we find the cluster we are looking for.
    Then we use this cluster as a filter to find all VMs.

    Something like this

    $vcName = 'vcsa.domain'

    $clusterName = 'MyCluster'


    Connect-CisServer -Server $vcName | Out-Null


    # Get the cluster

    $cis = Get-CisService -Name 'com.vmware.vcenter.cluster'

    $cluster = $cis.list() | where { $_.Name -eq $clusterName }


    # Get all VMs in the cluster

    $cis = Get-CisService -Name 'com.vmware.vcenter.vm'

    $filter = $cis.Help.list.filter.Create()

    $filter.clusters.Add($cluster.cluster)

    $cis.list($filter)


    Disconnect-CisServer -Server $vcName -Confirm:$false



  • 3.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 07:14 AM

    actually  i want to use rest api using powershell invoke-restmethod .

    below is what i got from net but for some reason it not working ..... just trying to understand that this is how any rest api is being consumed from powershell .

    can you have a look on it ??

    ###############################################

    # Configure the variables below for the vCenter

    ################################################

    $RESTAPIServer = "vcenterserver"

    # Prompting for credentials

    $Credentials = Get-Credential -Credential $null

    $RESTAPIUser = $Credentials.UserName

    $Credentials.Password | ConvertFrom-SecureString

    $RESTAPIPassword = $Credentials.GetNetworkCredential().password

    ################################################

    # Nothing to configure below this line - Starting the main function of the script

    ################################################

    # Adding certificate exception to prevent API errors

    ################################################

    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

    ################################################

    # Building vCenter API string & invoking REST API

    ################################################

    $BaseAuthURL = "https://" + $RESTAPIServer + "/rest/com/vmware/cis/"

    #$BaseAuthURL = "https://" + $RESTAPIServer + "/rest/cis/"

    $BaseURL = "https://" + $RESTAPIServer + "/rest/vcenter/"

    $vCenterSessionURL = $BaseAuthURL + "session"

    $Header = @{"Authorization" = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($RESTAPIUser+":"+$RESTAPIPassword))}

    $Type = "application/json"

    # Authenticating with API

    Try

    {

    $vCenterSessionResponse = Invoke-RestMethod -Uri $vCenterSessionURL -Headers $Header -Method POST -ContentType $Type

    }

    Catch

    {

    $_.Exception.ToString()

    $error[0] | Format-List -Force

    }

    # Extracting the session ID from the response

    $vCenterSessionHeader = @{'vmware-api-session-id' = $vCenterSessionResponse.value}

    ###############################################

    # Getting list of VMs

    ###############################################

    $VMListURL = $BaseURL+"vm"

    Try

    {

    $VMListJSON = Invoke-RestMethod -Method Get -Uri $VMListURL -TimeoutSec 100 -Headers $vCenterSessionHeader -ContentType $Type

    $VMList = $VMListJSON.value

    }

    Catch

    {

    $_.Exception.ToString()

    $error[0] | Format-List -Force

    }

    $VMList | Format-Table -AutoSize

    ###############################################

    # End of script

    ###############################################



  • 4.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 07:30 AM

    What exactly is not working?
    Making the connection, creating the session id or retrieving the VMs?



  • 5.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 07:45 AM

    it seems it failed while retriving vm url as it says line 55 .



  • 6.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 08:33 AM

    Your script works perfectly in my lab.
    Can you try adding the Verbose switch on the Invoke-RestMethod cmdlet?
    That way we can see the URI



  • 7.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 08:57 AM

    it means its not authenticated  are yu using administrator@vsphere.local id??



  • 8.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 08:59 AM

    Yes, I'm using the SSO administrator account.



  • 9.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 09:04 AM

    well it is not working for me with sso account also.

    from the screen shot it appears it stopped @ vm uri .



  • 10.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 09:19 AM

    Where are those 5 lines of HEX characters at the beginning of the output coming from?
    I don't see that when I run the script.



  • 11.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 09:46 AM

    Never mind, that's from the ConvertFrom-SecureString cmdlet.
    I commented that out.



  • 12.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 10:00 AM

    Out of curiosity, does the earlier code with the CisService work for you?



  • 13.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 10:32 AM

    I am yet to check the full.code but I was able to connect with connect-ciserver using both my domain and sso account.



  • 14.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 10:38 AM

    It's Connect-CisServer, the Connect-CiServer is for Cloud servers.



  • 15.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 10:46 AM

    I meant connect-cisserver .I was.able to consume some vami rest apis.but I thought of directly using it with invoke-restmethod (as joshua mentioned its fast and direct )using swagger provided by vsphere 6.5.



  • 16.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 10:49 AM

    No clue who this Joshua is, and I definitely don't see where Swagger comes into it with Invoke-RestMethod.
    Swagger is just a tool that in short allows to define API.
    The REST API and documentation are generated from these Swagger files.
    Using the REST API via the CisService or via Invoke-RestMethod has nothing to do with Swagger, underneath both methods use the same API



  • 17.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 11:08 AM

    Joshua is the author of this script.

    By swagger or api explorer  I wanted to say collection of all  rest api arranged in vsphere 6.5.

    I thought of using that script to see how we can use rest api using invoke-restmethod .

    Anything that has rest is exciting to explore further  



  • 18.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 11:11 AM

    Where was this script published?



  • 19.  RE: invoke-restmethod to use vsphere rest apis



  • 20.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 11:35 AM

    You might also want to have a look at UNDERSTANDING THE VMWARE REST API INTERFACE.

    It goes into the difference between Invoke-RestMethod and Invoke-WebRequest.



  • 21.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 11:46 AM

    Thanks but that code works for you  not for me.i m not sure how to get it working .



  • 22.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 11:58 AM

    I was just trying to explain that with Invoke-WebRequest you get the "raw" result, and often that is better when you want to examine the reason why a call failed.



  • 23.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 01:38 PM

    o

    i m trying to find out but do YU see any reason it failed looking at the screenshot I sent..



  • 24.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 20, 2019 06:37 PM

    Not really.
    Just to make sure, did you set the InvalidCertificateAction to Ignore?

    With an Invoke-WebRequest we can perhaps see more details about the actual error.



  • 25.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 21, 2019 06:32 AM

    i checked in other vcenterand found this to be working with invoke-restmethod

    i am trying to understand this a more

    1:when iamusing connect-cisserver iam using com.vmware.vcenter......        notation

    2:when i use invoke-restmethod i am using /rest/vcenter/                             notation

    can yu suggest some brief document to understand more about rest apis.



  • 26.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 21, 2019 06:47 AM

    Not sure what you are trying to ask with points 1 and 2.
    With Connect-CisServer, all the URI composing is done under the covers.
    Ultimately it generates the same REST API call.

    Did you already read the article I wrote, and to which I linked in an earlier reply?
    What is missing?
    What do you want to understand more?



  • 27.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 21, 2019 07:24 AM

    sorry if iam asking too many questions here .

    but what has happened i dont have administrator@vsphere.local password for this vcenter so i cant use connect-cisserver to get vcsa health .

    i am trying to create a similar invoke-restmethod way so that i can get vcsa health status using domain id .

    and for this method to work iam stuck at preparing base url and then system health url as shown in orange .if yu can check this works in yur test lab .

    ###############################################

    # Configure the variables below for the vCenter

    ################################################

    $RESTAPIServer = "vcenter1"

    # Prompting for credentials

    $Credentials = Get-Credential -Credential $null

    $RESTAPIUser = $Credentials.UserName

    $Credentials.Password | ConvertFrom-SecureString

    $RESTAPIPassword = $Credentials.GetNetworkCredential().password

    ################################################

    # Nothing to configure below this line - Starting the main function of the script

    ################################################

    # Adding certificate exception to prevent API errors

    ################################################

    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

    ################################################

    # Building vCenter API string & invoking REST API

    ################################################

    $BaseAuthURL = "https://" + $RESTAPIServer + "/rest/com/vmware/cis/"

    #$BaseAuthURL = "https://" + $RESTAPIServer + "/rest/cis/"

    #$BaseURL = "https://" + $RESTAPIServer + "/rest/vcenter/"

    $BaseURL = "https://" + $RESTAPIServer + "/rest/appliance/health"

    $vCenterSessionURL = $BaseAuthURL + "session"

    $Header = @{"Authorization" = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($RESTAPIUser+":"+$RESTAPIPassword))}

    $Type = "application/json"

    # Authenticating with API

    Try

    {

    $vCenterSessionResponse = Invoke-RestMethod -Uri $vCenterSessionURL -Headers $Header -Method POST -ContentType $Type -Verbose

    }

    Catch

    {

    $_.Exception.ToString()

    $error[0] | Format-List -Force

    }

    # Extracting the session ID from the response

    $vCenterSessionHeader = @{'vmware-api-session-id' = $vCenterSessionResponse.value}

    ###############################################

    # Getting list of VMs

    ###############################################

    #$VMListURL = $BaseURL+"cluster"

    $app_health_URL = $BaseURL+"system"

    Try

    {

    $systemhealth_json = Invoke-RestMethod -Method Get -Uri $app_health_URL -Headers $vCenterSessionHeader -ContentType $Type -Verbose

    $system_health = $systemhealth_json.value

    }

    Catch

    {

    $_.Exception.ToString()

    $error[0] | Format-List -Force

    }

    $system_health

    #$VMList | Format-Table -AutoSize

    ###############################################

    # End of script

    ###############################################



  • 28.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 21, 2019 07:27 AM

    Before I check that script, what kind of account are you using then?
    You do need an SSO account.



  • 29.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 21, 2019 07:54 AM

    for this iam using domain account (and getting vms code worked with this account).



  • 30.  RE: invoke-restmethod to use vsphere rest apis
    Best Answer

    Posted Jun 21, 2019 08:40 AM

    1. There is an error in the construction of the URI.
    The line should say

    $app_health_URL = $BaseURL,"system" -join '/'

    2. Depending on which component you query, you will need different credentials.
    The list of VMs is something you asked from the vCenter.
    And in the vCenter your AD account obviously has the authority to make that query.

    The system health is something you ask from the VAMI, the VCSA appliance.
    To be able to do that the account needs to be in the SystemConfiguration.BashShellAdministrators group.

    Is your AD account in there?



  • 31.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 21, 2019 11:15 AM

    Thanks I am going to run this code again.

    However if appliance  is joined to ad domain.

    Will it not authenticate to vami  by domain credential.

    However I am going to check what yu asked.



  • 32.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 21, 2019 11:20 AM

    Yes, that will allow you to use an AD account, but you still need the required permissions.
    Otherwise any AD account would be able to do anything in your VCSA, and that is probably not what you want.



  • 33.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 21, 2019 12:29 PM

    I am going to check this again .I thought that account will at least have read permission to use get method .



  • 34.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 21, 2019 12:41 PM

    No, it doesn't.
    If the account is not added to that group I mentioned earlier, you can't access the API for the appliance.



  • 35.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 21, 2019 12:52 PM

    Thanks I m going to check this one more time.



  • 36.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 21, 2019 01:12 PM

    Ask your admins to add the AD account to that group I mentioned



  • 37.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jun 25, 2019 08:42 AM

    i am checking this also .



  • 38.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jul 05, 2019 04:41 AM

    thnaksfor this but i am using account similar to administrator@vsphere.local priviledges .

    if you can suggest  connect-ciserver will fetch health  from below vami for vcsa.



  • 39.  RE: invoke-restmethod to use vsphere rest apis

    Posted Jul 05, 2019 05:15 AM

    i mean connect-cisserver.