获得token并执行OpenStack的API

搭建起一套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 


(完)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值