Ask Your Question
3

list all servers with python nova client

asked 2014-09-30 19:18:09 -0500

Dan Zerkle gravatar image

I need to fetch a list of all virtual machines, their IDs, and their names using the Python API.

This is easy enough from the command line. The following will do it:

nova list --all_tenants

However, I can't find the equivalent to the --all_tenants option for the Python API. The following produces an empty list:

result = nova_client.servers.list()
for server in result:
    print server;

What am I missing, here?

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
9

answered 2014-09-30 19:32:47 -0500

larsks gravatar image

One of the first places to look for API examples is in the code for the cli tools themselves.

First, you can typically add --debug to the command line, and you will see the REST API calls that the tool is making. This by itself can often suggest suggest what you need to pass to the Python API. E.g., for nova list, we can run:

$ nova --debug list --all-tenants
REQ: curl -i 'http://127.0.0.1:8774/v2/e4099fa0b2524798b9666d26c95e6f47/servers/detail?all_tenants=1' -X GET -H "X-Auth-Project-Id: admin" -H "User-Agent: python-novaclient" -H "Accept: application/json" -H "X-Auth-Token: ..."

Here you can see that it's passing the all_tenants=1 parameter to the remote API. If you look for occurrences of all_tenants in the novaclient code, you will eventually find the do_list method, which calls the API list method like this:

servers = cs.servers.list(detailed=detailed,
                          search_opts=search_opts)

And search_opts is a dictionary containing, among other things:

search_opts = {
        'all_tenants': args.all_tenants,
}

And it turns out that if we write our own code following that model:

for server in nc.servers.list(search_opts={'all_tenants': 1}):
    print server.id, server.name

It does exactly what we want.

Tangentially related: I've been building a repository with very, very simple examples of the various Python APIs; you can find it here:

edit flag offensive delete link more

Comments

1

Tested and working. Thank you!

If only this stuff were documented. Digging around in the source code of another application to find out how an API works is the hard way (but better than nothing!).

Dan Zerkle gravatar imageDan Zerkle ( 2014-09-30 20:13:30 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Get to know Ask OpenStack

Resources for moderators

Question Tools

4 followers

Stats

Asked: 2014-09-30 19:18:09 -0500

Seen: 9,418 times

Last updated: Sep 30 '14