Skip to content

Instantly share code, notes, and snippets.

@kaitoii11
Last active February 29, 2024 17:27
Show Gist options
  • Save kaitoii11/32baa9904b279a24da0d38328fe9363c to your computer and use it in GitHub Desktop.
Save kaitoii11/32baa9904b279a24da0d38328fe9363c to your computer and use it in GitHub Desktop.
Sample on how to use vCenter API
  • Authenticate to vCenter to get user credential.
# curl -k -X POST https://<FQDN or IP>/rest/com/vmware/cis/session -u <USERNAME>:<PASSWORD> | jq
{
  "value": "SESSIONID"
}
  • Save the session id to a variable
# ID=SESSIONID
  • Access the end point with the session id
# curl -k -X GET -H "vmware-api-session-id: $ID" https:/ /<VCENTERIP or FQDN>/rest/vcenter/vm |jq
{
  "value": [
    {
      "memory_size_MiB": 16384,
      "vm": "vm-1",
      "name": "VM01",
      "power_state": "POWERED_ON",
      "cpu_count": 4
    },
    {
      "memory_size_MiB": 16384,
      "vm": "vm-2",
      "name": "VM02",
      "power_state": "POWERED_ON",
      "cpu_count": 4
    }
  ]
}
# curl -k -X GET -H "vmware-api-session-id: $ID" https://<VCENTERIP or FQDN>/rest/vcenter/datastore |jq
{
  "value": [
    {
      "datastore": "datastore-1",
      "name": "DS1",
      "type": "VMFS",
      "free_space": 290276245504,
      "capacity": 291789340672
    },
    {
      "datastore": "datastore-2",
      "name": "DS2",
      "type": "VMFS",
      "free_space": 3349917204480,
      "capacity": 3599451029504
    }
  ]
}

List of apis can be found below

@mStirner
Copy link

I get a "Authentication required." for the first request

@kaitoii11
Copy link
Author

Thanks for the feedback! Some of the comments in the command were wrong so I fixed it up.
Hope it works on your end!

@mStirner
Copy link

mStirner commented Oct 12, 2021

Does not work for me :/
But got it working with following commands:

curl -k -i -u <username>:<password> -X POST -c cookie-jar.txt https://<host>/rest/com/vmware/cis/session
curl -k -b cookie-jar.txt https://<host>/rest/vcenter/vm | jq

@kaitoii11
Copy link
Author

Thanks for the commands!
I don't have a vSphere environment handy so I'll update the gist whenever I have the chance to test it!

@duanwei33
Copy link

Useful example! Thanks @kaitoii11

@wyike
Copy link

wyike commented Sep 9, 2023

Really useful, thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment