搭建起一套OpenStack的環境之後,若要運作指定的API怎麼做?OpenStack各個元件/項目也都是基于Web Service的,是以一樣用curl發HTTP請求即可。原理都是一樣。首先,通過提供租戶、使用者名和密碼,獲得認證用的token和指定API所在項目的URL;然後利用此token和該URL就可以運作想要執行的指定API了。下面是詳細代碼講解。
1. 利用get_token.sh獲得token和compute URL(因為我們後面将執行一個Nova的API). get_token.sh如下:
#!/bin/sh
export OS_AUTH_URL='http://172.16.1.2:5000/v2.0'
export OS_TENANT_NAME='admin'
export OS_USERNAME='admin'
export OS_PASSWORD='admin'
# Get Token
curl -X POST ${OS_AUTH_URL}/tokens -H "Content-Type: application/json" -d '{
"auth": {
"tenantName": "'"${OS_TENANT_NAME}"'",
"passwordCredentials": {
"username": "'"${OS_USERNAME}"'",
"password": "'"${OS_PASSWORD}"'"
}
}
}' | python -m json.tool > token.txt 2>&1
TOKEN=`python parse_token_file.py --token_file ./token.txt --get_token`
OS_COMPUTE_URL=`python parse_token_file.py --token_file ./token.txt --get_compute_url`
echo "export TOKEN=$TOKEN" > mytoken.txt
echo "export OS_COMPUTE_URL=$OS_COMPUTE_URL" >> mytoken.txt
在這其中,一個非常重要的分析腳本使用python寫的。它主要用來分析上述shell腳本中的curl指令所擷取到的HTTP Response. 關于該擷取token的curl指令參考https://developer.openstack.org/api-guide/quick-start/api-quick-start.html#openstack-api-quick-guide 而該python腳本為parse_token_file.py如下:
import argparse
import simplejson
import sys
# Return a dict representing json
def get_auth_result(TOKEN_FILE):
try:
with open(TOKEN_FILE, "r") as token_file:
body = token_file.read()
json_body = simplejson.loads(body)
except Exception as ex:
print("Error: %s" % ex)
json_body = None
finally:
return json_body
def get_token(json_body):
try:
token = json_body['access']['token']['id']
except Exception as ex:
print("Error: %s" % ex)
token = None
finally:
return token
def get_compute_url(json_body):
compute_url = None
try:
service_catalog = json_body['access']['serviceCatalog']
for service in service_catalog:
if service.get('name', None) == 'nova':
compute_url = service['endpoints'][0]['publicURL']
break
except Exception as ex:
print("Error: %s" % ex)
finally:
return compute_url
def main():
parser = argparse.ArgumentParser(prog="python %s" % sys.argv[0])
parser.add_argument("--token_file", dest='token_file', required=True,
help="Specify the token file which is generated by curl command")
parser.add_argument("--get_token", dest='need_token', action='store_true', default=False,
help="Parse the token file and return the token")
parser.add_argument("--get_compute_url", dest='need_compute_url', action='store_true', default=False,
help="Parse the token file and return the compute url")
args = parser.parse_args()
token_file = args.token_file
need_token = args.need_token
need_compute_url = args.need_compute_url
json_body = get_auth_result(token_file)
if json_body is None:
return
token = get_token(json_body)
if token is None:
print("Error: Token is none")
return -1
if need_token:
print(token)
if need_compute_url:
compute_url = get_compute_url(json_body)
if compute_url is not None:
print(compute_url)
else:
print("Error: ComputeURL is None")
if __name__ == "__main__":
main()
2. 最後,拿到token後,在其過期前,可以一直執行自己想要執行的API了,例如下面這個腳本exec_api.sh:
#!/bin/sh
source ./mytoken.txt
# Try Nova API
curl -X GET ${OS_COMPUTE_URL}/servers -H "Content-Type: application/json" -H "X-Auth-Token: ${TOKEN}" -s | python -m json.tool
(完)