华为云ECS服务API使用指南(1) - 获取虚拟机列表

Posted by 云谷计算 on January 17, 2018

华为云最大的特点之一是完全基于OpenStack建设,所以也能完美的支持所有OpenStack的API以及相关生态,包括各种OpenStack CLI,开发语言(Python, Go, Java…)绑定SDK等。目前华为云已经在以下region开放了API服务:

  • cn-north-1
  • cn-south-1
  • cn-east-2

华为云官方API文档比较模糊,这一系列文章用来介绍如何在华为云上使用OpenStack API/CLI/SDK.


Region & Endpoints

要使用OpenStack API或者是任何CLI, 首先必须知道Region列表和Endpoints列表,比如Keystone(IAM), Nova(ECS), Cinder(EVS)等,详细的列表,可以参考这里.

比如租户申请的虚拟机在华北区,那么:

  • Region: cn-north-1
  • Keystone(IAM) Endpont: https://iam.cn-north-1.myhwclouds.com
  • Nova(ECS) Endpont: https://ecs.cn-north-1.myhwclouds.com

IAM认证

采用Keystone V3 scoped auth, 具体请求参数和返回结果请参考OpenStack官方手册,这篇文章中,我们需要返回结果中的TOKEN和PROJECT_ID,来作为下一步获取虚拟机列表的参数。

Request Example:

{
    "auth": {
        "identity": {
            "methods": [
                "password"
            ],
            "password": {
                "user": {
                    "id": "ee4dfb6e5540447cb3741905149d9b6e",
                    "password": "devstacker"
                }
            }
        },
        "scope": {
            "project": {
                "id": "a6944d763bf64ee6a275f1263fae0352"
            }
        }
    }
} 

虚拟机列表

采用Nova V2.1 API, 具体请求参数可以参考官方API手册

代码实现

#!/bin/bash

# 华为云账号,不是email
HEC_USER_NAME='YOUR_HEC_USERNAME'
# 华为云密码
HEC_USER_PASSWD='YOUR_HEC_PASSWORD'

# Region&Endpoints,
# 具体定义请参考:http://developer.hwclouds.com/endpoint.html
HEC_REGION='cn-north-1'
HEC_IAM_ENDPOINT='https://iam.cn-north-1.myhwclouds.com'
HEC_ECS_ENDPOINT='https://ecs.cn-north-1.myhwclouds.com'

AUTH_PARAMS='{
  "auth": {
    "identity": {
      "methods": [
        "password"
      ],
      "password": {
        "user": {
          "name": '"\"$HEC_USER_NAME\""',
          "password": '"\"$HEC_USER_PASSWD\""',
          "domain": {
            "name": '"\"$HEC_USER_NAME\""'
          }
        }
      }
    },
   "scope": {
      "project": {
        "name": '"\"$HEC_REGION\""'
      }
    }
  }
}'

curl -s -i -X POST ${HEC_IAM_ENDPOINT}/v3/auth/tokens -H 'content-type: application/json' -d "$AUTH_PARAMS" > /tmp/hec_auth_res && {
    TOKEN=`cat /tmp/hec_auth_res | grep "X-Subject-Token"| awk '{print$2}'`
    echo "HEC Token is: $TOKEN"

    PROJECT_ID=`tail -n 1 /tmp/hec_auth_res|python -c 'import json,sys;print json.load(sys.stdin)["token"]["project"]["id"]'`
    echo "HEC Project ID is: $PROJECT_ID"

    curl -i -X GET ${HEC_ECS_ENDPOINT}/v2/${PROJECT_ID}/servers -H "X-Auth-Token:${TOKEN}"
}

更多相关华为云API参考代码,请访问 https://github.com/luohao-brian/openstack-api-examples