VMWare REST API 應用
REST API 這部分我一直都是一知半解,直到公司最近要用來查詢VMWare vCenter的狀態,才來研究一下
一直聽說API可以做很多事,對方如果有提供API就可以怎樣怎樣之類的
就來實作一下吧!!
關於REST/RESTful API的介紹請點我,我覺得這邊講得很簡單,應該你哥哥姊姊可以懂得程度(爸爸媽媽我不保證XD)
既然要來搞VMWare,當然就先看看對方提供那些API讓我們可以用啦!!
VMWare REST API Reference Document請點我
首先,要在Linux環境下要透過API來處理各種行為,首先要先用curl這個好用的工具
接著,假設我們要來看看這個vCenter的內容,官方是這樣寫的 :
所以,先用個curl來試看看
#curl https://"your vcenter IP"/rest/vcenter/datacenter
curl說,憑證有問題,人家是https耶!!不過不要擔心,它很貼心的跟你說,你可以用-k 來忽略
curl: (60) Peer's Certificate issuer is not recognized.
More details here: http://curl.haxx.se/docs/sslcerts.html
curl performs SSL certificate verification by default, using a "bundle"
of Certificate Authority (CA) public keys (CA certs). If the default
bundle file isn't adequate, you can specify an alternate file
using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
the bundle, the certificate verification probably failed due to a
problem with the certificate (it might be expired, or the name might
not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
the -k (or --insecure) option.
來,讓我們加入 -k 參數
curl -k https://(your vcenter IP)/rest/vcenter/datacenter
來,又報錯.....為何呢?他說 This method requires authentication
{"type":"com.vmware.vapi.std.errors.unauthenticated","value":{"messages":[{"args":[],"default_message":"This method requires authentication.","id":"vapi.method.authentication.required"}]
好.....問一下谷哥一下吧!!這個錯誤找半天,好不容易看到這篇
認證的部分需要我們帶入有權限的使用者,並且取得session id才能夠使用,請以下指令,其中並帶入你的vCenter administrator帳號及密碼
crul -X 參數代表接下要使用的method是POST/GET/...etc
# curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'vmware-use-header-authn: test' --header 'vmware-api-session-id: null' -u 'administrator:password' 'https://(your vcenter IP)/rest/com/vmware/cis/session'
接下來你會得到以下的session ID
{"value":"e6418a3a4860f0f7618e24f67a139a0d"}
拿到之後勒,把它帶入以下指令中
curl -sik -H 'Accept:application/json' -H "vmware-api-session-id:e6418a3a4860f0f7618e24f67a139a0d" -X GET https://(your vcenter IP)/rest/vcenter/datacenter/
得到以下資訊,拿到資訊了唷!!
HTTP/1.1 200 OK
Date: Thu, 08 Nov 2018 07:00:25 GMT
Content-Type: application/json
Transfer-Encoding: chunked
{"value":[{"name":"MyDatacenter","datacenter":"datacenter-2"}]}
如果你想看VM資訊的話,可以這樣下
curl -sik -H 'Accept:application/json' -H "vmware-api-session-id:e6418a3a4860f0f7618e24f67a139a0d" -X GET https://(your vcenter IP)/rest/vcenter/vm
進階一點應用,直接在遠端下curl讓guest O.S開關機