当前位置: 首页>>代码示例>>Python>>正文


Python ServiceManagementService.list_os_images方法代码示例

本文整理汇总了Python中azure.servicemanagement.ServiceManagementService.list_os_images方法的典型用法代码示例。如果您正苦于以下问题:Python ServiceManagementService.list_os_images方法的具体用法?Python ServiceManagementService.list_os_images怎么用?Python ServiceManagementService.list_os_images使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在azure.servicemanagement.ServiceManagementService的用法示例。


在下文中一共展示了ServiceManagementService.list_os_images方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: launch_node

# 需要导入模块: from azure.servicemanagement import ServiceManagementService [as 别名]
# 或者: from azure.servicemanagement.ServiceManagementService import list_os_images [as 别名]
def launch_node(node_id, creds, params, init, ssh_username, ssh_private_key):
    # "pip install azure"
    sms = ServiceManagementService(
        subscription_id='69581868-8a08-4d98-a5b0-1d111c616fc3',
        cert_file='/Users/dgriffin/certs/iOSWAToolkit.pem')
    for i in sms.list_os_images():
        print 'I is ', i.name, ' -- ', i.label, ' -- ', i.location, ' -- ', i.media_link
    media_link = \
        'http://opdemandstorage.blob.core.windows.net/communityimages/' + \
        'b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu_DAILY_BUILD-' + \
        'precise-12_04_2-LTS-amd64-server-20130702-en-us-30GB.vhd'
    config = LinuxConfigurationSet(user_name="ubuntu", user_password="opdemand")
    hard_disk = OSVirtualHardDisk(
        'b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu_DAILY_BUILD-' +
        'precise-12_04_2-LTS-amd64-server-20130702-en-us-30GB',
        media_link, disk_label='opdemandservice')
    ret = sms.create_virtual_machine_deployment(
        'opdemandservice', 'deploy1', 'production', 'opdemandservice2',
        'opdemandservice3', config, hard_disk)
       # service_name, deployment_name, deployment_slot, label, role_name
       # system_config, os_virtual_hard_disk
    print 'Ret ', ret
    return sms
开发者ID:Halfnhav,项目名称:deis,代码行数:25,代码来源:azuresms.py

示例2: __init__

# 需要导入模块: from azure.servicemanagement import ServiceManagementService [as 别名]
# 或者: from azure.servicemanagement.ServiceManagementService import list_os_images [as 别名]
class AzureServicesManager:
    # Storage
    container = 'vhds'
    windows_blob_url = 'blob.core.windows.net'

    # Linux
    linux_user = 'azureuser'
    linux_pass = 'Test123#'
    location = 'West US'
    # SSH Keys

    def __init__(self, subscription_id, cert_file):
        self.subscription_id = subscription_id
        self.cert_file = cert_file
        self.sms = ServiceManagementService(self.subscription_id, self.cert_file)

    @property
    def sms(self):
         return self.sms

    def list_locations(self):
        locations = self.sms.list_locations()
        for location in locations:
            print location

    def list_images(self):
        return self.sms.list_os_images()

    @utils.resource_not_found_handler
    def get_hosted_service(self, service_name):
        resp = self.sms.get_hosted_service_properties(service_name)
        properties = resp.hosted_service_properties
        return properties.__dict__

    def delete_hosted_service(self, service_name):
        res = self.sms.check_hosted_service_name_availability(service_name)
        if not res.result:
            return

        self.sms.delete_hosted_service(service_name)

    def create_hosted_service(self, os_user, service_name=None, random=False):
        if not service_name:
            service_name = self.generate_cloud_service_name(os_user, random)

        available = False

        while not available:
            res = self.sms.check_hosted_service_name_availability(service_name)
            if not res.result:
                service_name = self.generate_cloud_service_name(os_user,
                                                                random)
            else:
                available = True

        self.sms.create_hosted_service(service_name=service_name,
                                       label=service_name,
                                       location='West US')

        return service_name

    def create_virtual_machine(self, service_name, vm_name, image_name, role_size):
        media_link = self._get_media_link(vm_name)
        # Linux VM configuration
        hostname = '-'.join((vm_name, 'host'))
        linux_config = LinuxConfigurationSet(hostname,
                                             self.linux_user,
                                             self.linux_pass,
                                             True)

        # Hard disk for the OS
        os_hd = OSVirtualHardDisk(image_name, media_link)

        # Create vm
        result = self.sms.create_virtual_machine_deployment(
            service_name=service_name,  deployment_name=vm_name,
            deployment_slot='production', label=vm_name,
            role_name=vm_name, system_config=linux_config,
            os_virtual_hard_disk=os_hd,
            role_size=role_size
        )
        request_id = result.request_id

        return {
            'request_id': request_id,
            'media_link': media_link
        }

    def delete_virtual_machine(self, service_name, vm_name):
        resp = self.sms.delete_deployment(service_name, vm_name, True)
        self.sms.wait_for_operation_status(resp.request_id)
        result = self.sms.delete_hosted_service(service_name)
        return result

    def generate_cloud_service_name(self, os_user=None, random=False):
        if random:
            return utils.generate_random_name(10)

        return '-'.join((os_user, utils.generate_random_name(6)))

#.........这里部分代码省略.........
开发者ID:graceyu08,项目名称:azure-openstack-driver,代码行数:103,代码来源:azureclient.py

示例3: AzureInventory

# 需要导入模块: from azure.servicemanagement import ServiceManagementService [as 别名]
# 或者: from azure.servicemanagement.ServiceManagementService import list_os_images [as 别名]
class AzureInventory(object):
    def __init__(self):
        """Main execution path."""
        # Inventory grouped by display group
        self.inventory = {}
        # Index of deployment name -> host
        self.index = {}
        self.host_metadata = {}

        # Cache setting defaults.
        # These can be overridden in settings (see `read_settings`).
        cache_dir = os.path.expanduser('~')
        self.cache_path_cache = os.path.join(cache_dir, '.ansible-azure.cache')
        self.cache_path_index = os.path.join(cache_dir, '.ansible-azure.index')
        self.cache_max_age = 0

        # Read settings and parse CLI arguments
        self.read_settings()
        self.read_environment()
        self.parse_cli_args()

        # Initialize Azure ServiceManagementService
        self.sms = ServiceManagementService(self.subscription_id, self.cert_path)

        # Cache
        if self.args.refresh_cache:
            self.do_api_calls_update_cache()
        elif not self.is_cache_valid():
            self.do_api_calls_update_cache()

        if self.args.list_images:
            data_to_print = self.json_format_dict(self.get_images(), True)
        elif self.args.list or self.args.host:
            # Display list of nodes for inventory
            if len(self.inventory) == 0:
                data = json.loads(self.get_inventory_from_cache())
            else:
                data = self.inventory

            if self.args.host:
                data_to_print = self.get_host(self.args.host)
            else:
                # Add the `['_meta']['hostvars']` information.
                hostvars = {}
                if len(data) > 0:
                    for host in set([h for hosts in data.values() for h in hosts if h]):
                        hostvars[host] = self.get_host(host, jsonify=False)
                data['_meta'] = {'hostvars': hostvars}

                # JSONify the data.
                data_to_print = self.json_format_dict(data, pretty=True)
        print(data_to_print)

    def get_host(self, hostname, jsonify=True):
        """Return information about the given hostname, based on what
        the Windows Azure API provides.
        """
        if hostname not in self.host_metadata:
            return "No host found: %s" % json.dumps(self.host_metadata)
        if jsonify:
            return json.dumps(self.host_metadata[hostname])
        return self.host_metadata[hostname]

    def get_images(self):
        images = []
        for image in self.sms.list_os_images():
            if str(image.label).lower().find(self.args.list_images.lower()) >= 0:
                images.append(vars(image))
        return json.loads(json.dumps(images, default=lambda o: o.__dict__))

    def is_cache_valid(self):
        """Determines if the cache file has expired, or if it is still valid."""
        if os.path.isfile(self.cache_path_cache):
            mod_time = os.path.getmtime(self.cache_path_cache)
            current_time = time()
            if (mod_time + self.cache_max_age) > current_time:
                if os.path.isfile(self.cache_path_index):
                    return True
        return False

    def read_settings(self):
        """Reads the settings from the .ini file."""
        config = ConfigParser.SafeConfigParser()
        config.read(os.path.dirname(os.path.realpath(__file__)) + '/windows_azure.ini')

        # Credentials related
        if config.has_option('azure', 'subscription_id'):
            self.subscription_id = config.get('azure', 'subscription_id')
        if config.has_option('azure', 'cert_path'):
            self.cert_path = config.get('azure', 'cert_path')

        # Cache related
        if config.has_option('azure', 'cache_path'):
            cache_path = os.path.expandvars(os.path.expanduser(config.get('azure', 'cache_path')))
            self.cache_path_cache = os.path.join(cache_path, 'ansible-azure.cache')
            self.cache_path_index = os.path.join(cache_path, 'ansible-azure.index')
        if config.has_option('azure', 'cache_max_age'):
            self.cache_max_age = config.getint('azure', 'cache_max_age')

    def read_environment(self):
#.........这里部分代码省略.........
开发者ID:JaredPennella,项目名称:DevOps_Script,代码行数:103,代码来源:windows_azure.py

示例4: AzureNodeDriver

# 需要导入模块: from azure.servicemanagement import ServiceManagementService [as 别名]
# 或者: from azure.servicemanagement.ServiceManagementService import list_os_images [as 别名]
class AzureNodeDriver(NodeDriver):
    name = "Azure Node Provider"
    type = Provider.AZURE
    website = 'http://windowsazure.com'
    sms = None

    rolesizes = None

    NODE_STATE_MAP = {
        'RoleStateUnknown': NodeState.UNKNOWN,
        'CreatingVM': NodeState.PENDING,
        'StartingVM': NodeState.PENDING,
        'CreatingRole': NodeState.PENDING,
        'StartingRole': NodeState.PENDING,
        'ReadyRole': NodeState.RUNNING,
        'BusyRole': NodeState.PENDING,
        'StoppingRole': NodeState.PENDING,
        'StoppingVM': NodeState.PENDING,
        'DeletingVM': NodeState.PENDING,
        'StoppedVM': NodeState.STOPPED,
        'RestartingRole': NodeState.REBOOTING,
        'CyclingRole': NodeState.TERMINATED,
        'FailedStartingRole': NodeState.TERMINATED,
        'FailedStartingVM': NodeState.TERMINATED,
        'UnresponsiveRole': NodeState.TERMINATED,
        'StoppedDeallocated': NodeState.TERMINATED,
    }

    def __init__(self, subscription_id=None, key_file=None, **kwargs):
        """
        subscription_id contains the Azure subscription id
        in the form of GUID key_file contains
        the Azure X509 certificate in .pem form
        """
        self.subscription_id = subscription_id
        self.key_file = key_file
        self.sms = ServiceManagementService(subscription_id, key_file)

        super(AzureNodeDriver, self).__init__(
            self.subscription_id,
            self.key_file,
            secure=True,
            **kwargs)

    def list_sizes(self):
        """
        Lists all sizes from azure

        :rtype: ``list`` of :class:`NodeSize`
        """
        if self.rolesizes is None:
            # refresh rolesizes
            data = self.sms.list_role_sizes()
            self.rolesizes = [self._to_node_size(i) for i in data]
        return self.rolesizes

    def list_images(self, location=None):
        """
        Lists all sizes from azure

        :rtype: ``list`` of :class:`NodeSize`
        """
        data = self.sms.list_os_images()
        images = [self._to_image(i) for i in data]

        if location is not None:
            images = [image for image in images
                      if location in image.extra["location"]]
        return images

    def list_locations(self):
        """
        Lists all Location from azure

        :rtype: ``list`` of :class:`NodeLocation`
        """
        data = self.sms.list_locations()
        locations = [self._to_location(i) for i in data]
        return locations

    def list_virtual_net(self):
        """
        List all VirtualNetworkSites

        :rtype: ``list`` of :class:`VirtualNetwork`
        """
        data = self.sms.list_virtual_network_sites()
        virtualnets = [self._to_virtual_network(i) for i in data]
        return virtualnets

    def create_node(self,
                    name,
                    image,
                    size,
                    storage,
                    service_name,
                    vm_user,
                    vm_password,
                    location=None,
                    affinity_group=None,
#.........这里部分代码省略.........
开发者ID:zhitongLBN,项目名称:Libcloud-Custom,代码行数:103,代码来源:azure_driver.py

示例5: AzureInventory

# 需要导入模块: from azure.servicemanagement import ServiceManagementService [as 别名]
# 或者: from azure.servicemanagement.ServiceManagementService import list_os_images [as 别名]
class AzureInventory(object):
    def __init__(self):
        """Main execution path."""
        # Inventory grouped by display group
        self.inventory = {}
        # Index of deployment name -> host
        self.index = {}

        # Read settings and parse CLI arguments
        self.read_settings()
        self.read_environment()
        self.parse_cli_args()

        # Initialize Azure ServiceManagementService
        self.sms = ServiceManagementService(self.subscription_id, self.cert_path)

        # Cache
        if self.args.refresh_cache:
            self.do_api_calls_update_cache()
        elif not self.is_cache_valid():
            self.do_api_calls_update_cache()

        if self.args.list_images:
            data_to_print = self.json_format_dict(self.get_images(), True)
        elif self.args.list:
            # Display list of nodes for inventory
            if len(self.inventory) == 0:
                data_to_print = self.get_inventory_from_cache()
            else:
                data_to_print = self.json_format_dict(self.inventory, True)

        print data_to_print

    def get_images(self):
        images = []
        for image in self.sms.list_os_images():
            if str(image.label).lower().find(self.args.list_images.lower()) >= 0:
                images.append(vars(image))
        return json.loads(json.dumps(images, default=lambda o: o.__dict__))

    def is_cache_valid(self):
        """Determines if the cache file has expired, or if it is still valid."""
        if os.path.isfile(self.cache_path_cache):
            mod_time = os.path.getmtime(self.cache_path_cache)
            current_time = time()
            if (mod_time + self.cache_max_age) > current_time:
                if os.path.isfile(self.cache_path_index):
                    return True
        return False

    def read_settings(self):
        """Reads the settings from the .ini file."""
        config = ConfigParser.SafeConfigParser()
        config.read(os.path.dirname(os.path.realpath(__file__)) + '/windows_azure.ini')

        # Credentials related
        if config.has_option('azure', 'subscription_id'):
            self.subscription_id = config.get('azure', 'subscription_id')
        if config.has_option('azure', 'cert_path'):
            self.cert_path = config.get('azure', 'cert_path')

        # Cache related
        if config.has_option('azure', 'cache_path'):
            cache_path = config.get('azure', 'cache_path')
            self.cache_path_cache = cache_path + "/ansible-azure.cache"
            self.cache_path_index = cache_path + "/ansible-azure.index"
        if config.has_option('azure', 'cache_max_age'):
            self.cache_max_age = config.getint('azure', 'cache_max_age')

    def read_environment(self):
        ''' Reads the settings from environment variables '''
        # Credentials
        if os.getenv("AZURE_SUBSCRIPTION_ID"): self.subscription_id = os.getenv("AZURE_SUBSCRIPTION_ID")
        if os.getenv("AZURE_CERT_PATH"):       self.cert_path = os.getenv("AZURE_CERT_PATH")


    def parse_cli_args(self):
        """Command line argument processing"""
        parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on Azure')
        parser.add_argument('--list', action='store_true', default=True,
                           help='List nodes (default: True)')
        parser.add_argument('--list-images', action='store',
                           help='Get all available images.')
        parser.add_argument('--refresh-cache', action='store_true', default=False,
                           help='Force refresh of cache by making API requests to Azure (default: False - use cache files)')
        self.args = parser.parse_args()

    def do_api_calls_update_cache(self):
        """Do API calls, and save data in cache files."""
        self.add_cloud_services()
        self.write_to_cache(self.inventory, self.cache_path_cache)
        self.write_to_cache(self.index, self.cache_path_index)

    def add_cloud_services(self):
        """Makes an Azure API call to get the list of cloud services."""
        try:
            for cloud_service in self.sms.list_hosted_services():
                self.add_deployments(cloud_service)
        except WindowsAzureError as e:
            print "Looks like Azure's API is down:"
#.........这里部分代码省略.........
开发者ID:pintostack,项目名称:core,代码行数:103,代码来源:windows_azure.py

示例6: get_certificate_from_publish_settings

# 需要导入模块: from azure.servicemanagement import ServiceManagementService [as 别名]
# 或者: from azure.servicemanagement.ServiceManagementService import list_os_images [as 别名]
    subscription_id = '8ea1a328-9162-4a6e-9cdc-fcc8d6766608'

    pem_file = './azure/certs/azure_client.pem'

    subscription_id = get_certificate_from_publish_settings(
        publish_settings_path='./azure/certs/subscription.publishsettings',
        path_to_write_certificate=pem_file,
        subscription_id=subscription_id
    )

    sms = ServiceManagementService(subscription_id, pem_file)
    
    if not os.path.exists('./azure/data'):
        os.mkdir('./azure/data')

    result = sms.list_os_images()
    process_sms_list(result.images, './azure/data/azure_os_images.csv')
    print ('Azure OS images saved in azure_os_images.csv')

    result = sms.list_vm_images()
    process_sms_list(result.vm_images, './azure/data/azure_vm_images.csv')
    print ('Azure VM images saved in azure_vm_images.csv')

    result = sms.list_role_sizes()
    process_sms_list(result.role_sizes, './azure/data/azure_role_sizes.csv')
    print ('Azure Role sizes saved in azure_role_sizes.csv')

    result = sms.list_locations()
    process_sms_list(result.locations, './azure/data/azure_locations.csv')
    print ('Azure Locations saved in azure_locations.csv')
开发者ID:dominoFire,项目名称:sweeper-extractor,代码行数:32,代码来源:list_services.py


注:本文中的azure.servicemanagement.ServiceManagementService.list_os_images方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。