设为首页 收藏本站
查看: 753|回复: 0

[经验分享] Cloud in Action: Manage and Manipulate OpenStack with CLI, SDK and API

[复制链接]

尚未签到

发表于 2018-5-30 12:53:31 | 显示全部楼层 |阅读模式
   Cloud in Action: Manage and Manipulate OpenStack with CLI, SDK and API
  
   薛国锋    xueguofeng2011@gmail.com
  

  Today we are going to experience the three ways to manage and manipulate OpenStack –CLI, SDK and API; and then develop a simple Hybrid Cloud application with Python to exchange data between Amazon Web Services and OpenStack.
DSC0000.png

  

  API, SDK and CLI
  There are three ways you can use Openstack:
  
  RESTful API, you can send the requests directly using HTTP GET or POST via a Web Browser, your program code or using cURL to the service endpoints (API Gateway) of OpenStack and issue your commands. Using the OpenStack APIs, you can launch server instances, create images, assign metadata to instances and images, create storage containers and objects, and complete other actions in the OpenStack-based Cloud.
  
  SDK, aka the language-level API. Making the API calls directly could be cumbersome and you have to repeat a lot of template code time and again, and handle the HTTP status code and response carefully. SDK provides the set of lanuage binds in Java, Python, Go and C++ etc, and it can help build the HTTP requests and make the API calls, allowing us to access OpenStack in a manner consistent with high-level language standards such as make function calls.
  
  CLI, OpenStack also provied the command-line interfaces with OpenStackClients, along with the natvie Python API bindings for Compute,Identity,Image,Object Store and Block Storage etc. We have used CLI many times during the Openstack installation and configuration.
  
DSC0001.png
  

  OpenStack API: Making the RESTful API calls to OpenStack
  https://developer.openstack.org/api-guide/quick-start/
  

DSC0002.png

  

  // To authenticate with OpenStack KeyStone
  // and get the token and service catalog via cURL or Postman

  URL: http://10.0.0.11:5000/v2.0/tokens
  Method: POST
  Headers: Content-Type:application/json
  Data: {"auth":{"tenantName":"admin","passwordCredentials":{"username":"admin","password":"ipcc2014"}}}   
  
  Response:
  The project id: "448c4d583e1240ee93b0800c382fd494";
  The token: "gAAAAABZ9hCPjL9D6uz3lqR6spcDgBWaR28VtkVZfGzcVTh-pPXPzvUElKuHLgiAekm7gVObUDGVjXdfM6ZqslYynFIf2aRKLdKZuP2W3Ps8yw70ZRISCFtRxN8wsOh-iEc1-ZUm0rqd9co_m7xSQTqRzFNtKKpAftAHbZYb58d0H2YofvHSUAk"
DSC0003.png

  

  // To make HTTP requests to Nova with the received token and project ID, and get the instance info
  URL: http://10.0.0.11:8774/v2.1/448c4d583e1240ee93b0800c382fd494/servers
  Method: GET
  Headers:
  Accept:application/json
  Content-Type:application/json
  X-Auth-Token:gAAAAABZ9hCPjL9D6uz3lqR6spcDgBWaR28VtkVZfGzcVTh-pPXPzvUElKuHLgiAekm7gVObUDGVjXdfM6ZqslYynFIf2aRKLdKZuP2W3Ps8yw70ZRISCFtRxN8wsOh-iEc1-ZUm0rqd9co_m7xSQTqRzFNtKKpAftAHbZYb58d0H2YofvHSUAk
  
  Response:
DSC0004.png

  

  OpenStack SDK(Python): Making functional calls with the native Python bindings

  https://wiki.openstack.org/wiki/SDKs
  https://wiki.openstack.org/wiki/OpenStackClients
  
  // To install pip and python-openstackclient
  sudo apt-get installpython-pip
  sudo apt-get install curl
  sudo pip installpython-keystoneclient
  sudo pip installpython-novaclient
  sudo pip installpython-glanceclient
  
  // To list all the images from OpenStack Glance
  import keystoneclient.v2_0.client as ksclient
  import glanceclient
  
  # To authenticate with Keystone and get thetoken and servive catalog
  keystone =ksclient.Client(auth_url="http://10.0.0.11:5000/v2.0",
                                                username="admin",password="ipcc2014",tenant_name="admin")
  print(keystone.auth_token)                 
  
  # To get the service endpoint of Glance
  endpoint = keystone.service_catalog.url_for(service_type='image',
                                              endpoint_type='publicURL')
  # To list all the images
  glance = glanceclient.Client('2',endpoint,token=keystone.auth_token)
  for image in glance.images.list():
                  print(image.id+ " " + image.name)
  
  // To upload the image to OpenStack Glance
  import keystoneclient.v2_0.client as ksclient
  import glanceclient
  
  def get_keystone_creds():
      d ={}
     d['username'] = 'admin'
     d['password'] = 'ipcc2014'
     d['auth_url'] = 'http://10.0.0.11:5000/v2.0'
     d['tenant_name'] = 'admin'
     return d
  creds = get_keystone_creds()
  keystone = ksclient.Client(**creds)
  
  endpoint = keystone.service_catalog.url_for(service_type='image',endpoint_type='publicURL')
  glance =glanceclient.Client('2',endpoint,token=keystone.auth_token)
  
  newimage =glance.images.create(name="cirros_0_3_5", disk_format="qcow2",container_format="bare")
  glance.images.upload(newimage.id,open('cirros-0.3.5-x86_64-disk.img', 'rb'))
  
  // To list all instances
  from novaclient import client
  # Project ID: 448c4d583e1240ee93b0800c382fd494
  nova = client.Client(2,'admin','ipcc2014','448c4d583e1240ee93b0800c382fd494','http://10.0.0.11:5000/v2.0')
  print(nova.servers.list())
  print(nova.flavors.list())
  
  OpenStack CLI: Manipulating OpenStack directly with commands
  https://docs.openstack.org/python-openstackclient/latest/cli/
   DSC0005.png
DSC0006.png

  

  AWS SDK(Python): Making functional calls
   https://boto3.readthedocs.io/en/latest/guide/quickstart.html
  
  // Install the latest Boto 3 release via pip
  pip install boto3
  
  // Set up authentication credentials and the defaultregion
  // You need to create a AWS account
  
  gedit~/.aws/config
  gedit ~/.aws/credentials
DSC0007.png

  // To list all the buckets and keys from AWS S3
  import boto3
  import botocore
  
  s3 = boto3.resource('s3')
          
  for bucket in s3.buckets.all():
     print(bucket.name)
  
  for bucket in s3.buckets.all():
                                  print(bucket.name)
                                  forkey in bucket.objects.all():
                                                                  print("----" + key.key)
  
  # To create a bucket and upload the object
  '''
  s3.create_bucket(Bucket='xgf20171028',CreateBucketConfiguration={
     'LocationConstraint': 'us-west-2'})
  data = open('test001.jpg', 'rb')
  s3.Bucket('xgftemp20170520').put_object(Key='test001.jpg',Body=data)
  '''
  

  Develop a simple Hybrid Cloud application
  In the application, we will download the img file object from AWS S3, creat an image in OpenStack Glance and launch several instances with the image to simulate the data exchange between the Private and Public Cloud.
  

  ################################################################
  # For AWS
  import boto3
  import botocore
  
  # For OpenStack
  import keystoneclient.v2_0.client as ksclient
  import glanceclient
  from novaclient import client
  ################################################################
  s3 = boto3.resource('s3')

  
  print("To list all the buckets and keys in AWS S3")
  for bucket in s3.buckets.all():
                                  print(bucket.name)
                                  forkey in bucket.objects.all():
                                                                  print("----" + key.key)
  
  BUCKET_NAME = 'xgf20171028'
  KEY = 'cirros-0.3.5-x86_64-disk.img'
  
  print("To download the img object from AWS S3:")
  try:
     s3.Bucket(BUCKET_NAME).download_file(KEY,'cirros-0.3.5-x86_64-disk.img')
     print( "cirros-0.3.5-x86_64-disk.img is just downloaded from AWS S3to the local HD")
  except botocore.exceptions.ClientError as e:
      ife.response['Error']['Code'] == "404":
         print("The object does not exist.")
     else:
         raise      
  ################################################################

  keystone =ksclient.Client(auth_url="http://10.0.0.11:5000/v2.0",username="admin",password="ipcc2014",tenant_name="admin")

  
  # get the endpoint of image service
  endpoint =keystone.service_catalog.url_for(service_type='image',endpoint_type='publicURL')
  print('the endpoint of OpenStack Glance: ' +endpoint)  
  
  glance =glanceclient.Client('2',endpoint,token=keystone.auth_token)
  
  print( "To list all the images inGlance:")
  for image in glance.images.list():
                  print(image.id+ " " + image.name)
  
  # Tocreate a new image by glance with what was just downloaded from AWS S3  
  newimage =glance.images.create(name="cirros_0_3_5", disk_format="qcow2",container_format="bare")
  glance.images.upload(newimage.id,open('cirros-0.3.5-x86_64-disk.img', 'rb'))
  print( "cirros-0.3.5-x86_64-disk.img isjust uploaded to OpenStack Glance")
     
  print( "To list all the images inGlance:")   
  for image in glance.images.list():
                  print(image.id+ " " + image.name)
  ################################################################
   # the project ID of admin:'448c4d583e1240ee93b0800c382fd494'
  nova =client.Client(2,'admin','ipcc2014','448c4d583e1240ee93b0800c382fd494','http://10.0.0.11:5000/v2.0')
  
  print( "To list all the VMs in OpenStack:")   
  print(nova.servers.list())
  
  # xgf_provider ID:995ccb97-fa06-403b-961c-5c11d8b24067
  net_id = "995ccb97-fa06-403b-961c-5c11d8b24067"
  nics = [{"net-id": net_id,"v4-fixed-ip": ''}]
  flavor =nova.flavors.find(name="m1.nano")
  
  print( "To create 3 VMs:")  
  nova.servers.create("xgf101",newimage, flavor, nics=nics)
  nova.servers.create("xgf102",newimage, flavor, nics=nics)
  nova.servers.create("xgf103",newimage, flavor, nics=nics)
  
  print( "To list all the VMs inOpenStack:")   
  print(nova.servers.list())
  ################################################################
  

DSC0008.png

  

  

  

  

                             
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-483126-1-1.html 上篇帖子: Cloud in Action: Install and Deploy the Self 下篇帖子: keystone之权限认证功能openstack
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表