Python OpenStack SDK获取特定实例元数据

发布于 2025-01-19 15:41:27 字数 97 浏览 1 评论 0原文

我正在寻找一种方法,在 Python 中使用 OpenStack SDK 获取有关给定区域和项目的实例的特定元数据。我只想获取 id、名称、IP 地址和密钥名称。我想从“计算”开始

I am looking for a way, in Python to use the OpenStack SDK to get specific metadata about an instance for a given region and project. I am looking to only get the id, name, ip address and key name. I was thinking of starting with "compute"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天赋异禀 2025-01-26 15:41:27

我使用OpenStack Swift Python API有基本的工作,如下所示:

“ SwiftSearch.py​​”

import logging
import pprint
from optparse import OptionParser

from swiftclient.service import SwiftService, SwiftError

logger = None
debugLevel = 0

def swift_search(container, search_field, search_value):
    global logger
    global debugLevel

    stat_search_field = 'x-object-meta-'+search_field

    with SwiftService() as swift:
        objects = []
        try:
            list_parts_gen = swift.list(container=container)
            for page in list_parts_gen:
                if page["success"]:
                    for item in page["listing"]:
                        if  (debugLevel > 0): print('list: {} item: {}'.format(item['name'], item))
                        objects.append(item['name'])
                else:
                    raise page["error"]

            if (debugLevel > 0): print('list: objects.len:',len(objects))

            header_data = {}
            stats_it = swift.stat(container=container, objects=objects)
            for stat_res in stats_it:
                if stat_res['success']:
                    # header_data[stat_res['object']] = stat_res['headers']
                    if (stat_search_field in stat_res['headers']):
                        if (debugLevel > 0): print('stat_search_field:',stat_search_field, stat_res['headers'][stat_search_field])

                        if (search_value is None):
                            header_data[stat_res['object']] = {
                                stat_search_field: stat_res['headers'][stat_search_field]
                            }
                        elif (stat_res['headers'][stat_search_field] == search_value):
                            header_data[stat_res['object']] = {
                                stat_search_field: stat_res['headers'][stat_search_field]
                            }
                else:
                    logger.error(
                        'Failed to retrieve stats for %s' % stat_res['object']
                    )
            pprint.pprint(header_data)

        except SwiftError as e:
            logger.error(e.value)

def main():
    global logger
    global debugLevel

    parser = OptionParser()

    parser.add_option("--container", type="string",\
                      help="container name to search", \
                      dest="container",
                      default='user_uploads')

    parser.add_option("--field", type="string",\
                      help="stat field to query", \
                      dest="field",
                      default='stnid')

    parser.add_option("--value", type="string",\
                      help="stat field match value", \
                      dest="value",
                      default=None)

    parser.add_option("--debuglevel", action="store", \
                      type="int", nargs=1, dest="debuglevel", default=0)

    (options, args) = parser.parse_args()
    container = options.container
    search_field = options.field
    search_value = options.value
    debugLevel = options.debuglevel

    logging.basicConfig(level=logging.ERROR)
    logging.getLogger("requests").setLevel(logging.CRITICAL)
    logging.getLogger("swiftclient").setLevel(logging.CRITICAL)
    logger = logging.getLogger(__name__)

    swift_search(container, search_field, search_value)

if __name__ == "__main__":
    main()

以下是运行它的结果:

python ./swiftsearch.py --container user_uploads --field=stnid --value=AMOSD
{'AMOSD-gust_spd_max.png': {'x-object-meta-stnid': 'AMOSD'}}

另外,您必须使用附加的元数据上传,如下所示:

upload --meta stnid:AMOSD --object-name AMOSD-gust_spd_max.png user_uploads AMOSD-gust_spd_max.png

对于我的测试,我也在使用。单个实例OpenStack Swift实例的Docker容器:
https://hub.docker.com/r/fnndsc/docker-swift-只有一个

此解决方案并不是很棒的,因为它必须获取所有元素和统计数据元素中所有元素的列表,以使其元数据进行过滤 - 订单2N算法。

I have something rudimentary working using the openstack swift python api as follows:

"swiftsearch.py"

import logging
import pprint
from optparse import OptionParser

from swiftclient.service import SwiftService, SwiftError

logger = None
debugLevel = 0

def swift_search(container, search_field, search_value):
    global logger
    global debugLevel

    stat_search_field = 'x-object-meta-'+search_field

    with SwiftService() as swift:
        objects = []
        try:
            list_parts_gen = swift.list(container=container)
            for page in list_parts_gen:
                if page["success"]:
                    for item in page["listing"]:
                        if  (debugLevel > 0): print('list: {} item: {}'.format(item['name'], item))
                        objects.append(item['name'])
                else:
                    raise page["error"]

            if (debugLevel > 0): print('list: objects.len:',len(objects))

            header_data = {}
            stats_it = swift.stat(container=container, objects=objects)
            for stat_res in stats_it:
                if stat_res['success']:
                    # header_data[stat_res['object']] = stat_res['headers']
                    if (stat_search_field in stat_res['headers']):
                        if (debugLevel > 0): print('stat_search_field:',stat_search_field, stat_res['headers'][stat_search_field])

                        if (search_value is None):
                            header_data[stat_res['object']] = {
                                stat_search_field: stat_res['headers'][stat_search_field]
                            }
                        elif (stat_res['headers'][stat_search_field] == search_value):
                            header_data[stat_res['object']] = {
                                stat_search_field: stat_res['headers'][stat_search_field]
                            }
                else:
                    logger.error(
                        'Failed to retrieve stats for %s' % stat_res['object']
                    )
            pprint.pprint(header_data)

        except SwiftError as e:
            logger.error(e.value)

def main():
    global logger
    global debugLevel

    parser = OptionParser()

    parser.add_option("--container", type="string",\
                      help="container name to search", \
                      dest="container",
                      default='user_uploads')

    parser.add_option("--field", type="string",\
                      help="stat field to query", \
                      dest="field",
                      default='stnid')

    parser.add_option("--value", type="string",\
                      help="stat field match value", \
                      dest="value",
                      default=None)

    parser.add_option("--debuglevel", action="store", \
                      type="int", nargs=1, dest="debuglevel", default=0)

    (options, args) = parser.parse_args()
    container = options.container
    search_field = options.field
    search_value = options.value
    debugLevel = options.debuglevel

    logging.basicConfig(level=logging.ERROR)
    logging.getLogger("requests").setLevel(logging.CRITICAL)
    logging.getLogger("swiftclient").setLevel(logging.CRITICAL)
    logger = logging.getLogger(__name__)

    swift_search(container, search_field, search_value)

if __name__ == "__main__":
    main()

here are the results from running it:

python ./swiftsearch.py --container user_uploads --field=stnid --value=AMOSD
{'AMOSD-gust_spd_max.png': {'x-object-meta-stnid': 'AMOSD'}}

also, you must upload your objects with metadata attached like as follows:

upload --meta stnid:AMOSD --object-name AMOSD-gust_spd_max.png user_uploads AMOSD-gust_spd_max.png

also for my tests, I was using the docker container for a single instance openstack swift instance:
https://hub.docker.com/r/fnndsc/docker-swift-onlyone

This solution isn't great in that it has to get the list of all elements and stat all elements in the container to get their metadata to filter on - an order 2n algorithm.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文