### Install Project Dependencies Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/contributor/setup.rst Installs the necessary Python dependencies for the OpenStack SDK project using pip and a requirements file. This is required for local development and running example scripts. ```shell (sdk3)$ pip install -r requirements.txt ``` -------------------------------- ### YAML Example: Advanced clouds.yaml Configuration Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/multi-cloud-demo.rst A more complex clouds.yaml example for 'my-vexxhost' that specifies identity API version and an image endpoint override. It also shows authentication details for a specific project. ```yaml my-vexxhost: identity_api_version: 3 image_endpoint_override: https://image-ca-ymq-1.vexxhost.net/v2 profile: vexxhost auth: user_domain_id: default project_domain_id: default project_name: d8af8a8f-a573-48e6-898a-af333b970a2d username: 0b8c435b-cc4d-4e05-8a47-a2ada0539af1 ``` -------------------------------- ### Create DNS Zone using OpenStack SDK Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/dns.rst This example demonstrates how to create a new DNS zone. It requires a connection object and a domain name, returning the newly created zone resource. ```python from openstack import connection def create_zone(conn, domain_name): print(f'Creating zone: {domain_name}') zone = conn.dns.create_zone(name=domain_name) print(f'Created zone: {zone.id}') return zone ``` -------------------------------- ### YAML Example: Basic clouds.yaml Configuration Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/multi-cloud-demo.rst A simple example of a clouds.yaml file demonstrating configuration for a named cloud 'my-citycloud' referencing a 'citycloud' profile. It includes authentication details such as username and project ID. ```yaml clouds: my-citycloud: profile: citycloud auth: username: mordred project_id: 65222a4d09ea4c68934fa1028c77f394 user_domain_id: d0919bd5e8d74e49adf0e145807ffc38 project_domain_id: d0919bd5e8d74e49adf0e145807ffc38 ``` -------------------------------- ### YAML Example: Secure Password Configuration Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/multi-cloud-demo.rst An example of a secure.yaml file, which can be used to overlay secrets onto a clouds.yaml file. This example shows how to specify the password for the 'my-citycloud' configuration. ```yaml clouds: my-citycloud: auth: password: XXXXXXXX ``` -------------------------------- ### List DNS Zones using OpenStack SDK Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/dns.rst This example demonstrates how to list all DNS zones within your OpenStack cloud. It requires an active connection object and returns a list of zone resources. ```python from openstack import connection def list_zones(conn): print('Listing zones:') for zone in conn.dns.zones(): print(f" {zone.name} ({zone.id})") ``` -------------------------------- ### List DNS Recordsets using OpenStack SDK Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/dns.rst This example shows how to list all DNS recordsets within a specific zone. It requires a connection object and the zone ID, returning a list of recordset resources. ```python from openstack import connection def list_recordsets(conn, zone_id): print(f'Listing recordsets for zone {zone_id}:') for recordset in conn.dns.recordsets(zone_id): print(f" {recordset.name}. ({recordset.type})") ``` -------------------------------- ### Example clouds.yaml Configuration Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/config/configuration.rst A comprehensive example of a clouds.yaml file, illustrating how to define multiple cloud profiles with authentication details, region names, and service-specific settings like DNS API version. This allows for easy management of different OpenStack environments. ```yaml clouds: mtvexx: profile: https://vexxhost.com auth: username: mordred@inaugust.com password: XXXXXXXXX project_name: mordred@inaugust.com region_name: ca-ymq-1 dns_api_version: 1 mordred: region_name: RegionOne auth: username: 'mordred' password: XXXXXXX project_name: 'shade' auth_url: 'https://montytaylor-sjc.openstack.blueboxgrid.com:5001/v2.0' infra: profile: rackspace auth: username: openstackci password: XXXXXXXX project_id: 610275 regions: - DFW - ORD - IAD ``` -------------------------------- ### YAML Example: Internap Cloud Configuration Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/multi-cloud-demo.rst A detailed clouds.yaml example for 'my-internap' that does not use a profile. It includes specific network configurations for the 'ams01' region, defining routing and default interface properties. ```yaml my-internap: auth: auth_url: https://identity.api.cloud.inap.com username: api-55f9a00fb2619 project_name: inap-17037 identity_api_version: 3 floating_ip_source: None regions: - name: ams01 values: networks: - name: inap-17037-WAN1654 routes_externally: true default_interface: true - name: inap-17037-LAN3631 routes_externally: false ``` -------------------------------- ### Create DNS Recordset using OpenStack SDK Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/dns.rst This example demonstrates how to create a new DNS recordset within a zone. It requires a connection object, zone ID, and recordset details, returning the new recordset resource. ```python from openstack import connection def create_recordset(conn, zone_id, name, record_type, records): print(f'Creating recordset {name} in zone {zone_id}') recordset = conn.dns.create_recordset( zone_id=zone_id, name=name, type=record_type, records=records ) print(f'Created recordset: {recordset.id}') return recordset ``` -------------------------------- ### Install tox Test Runner Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/contributor/setup.rst Installs the 'tox' test runner into an active Python virtual environment using pip. Tox is used to run tests across multiple Python versions. ```shell (sdk3)$ pip install tox ``` -------------------------------- ### SDK Connection Object Examples Source: https://github.com/openstack/openstacksdk/blob/master/SHADE-MERGE-TODO.rst Demonstrates how to interact with the OpenStack cloud using the SDK's connection object, showcasing high-level resource interfaces, SDK service/object interfaces, and direct REST passthrough capabilities. ```python connection = connection.Connection() servers = connection.compute.servers() server_response = connection.compute.get('/servers') ``` ```python conn = connection.Connection() servers = conn.list_servers() # High-level resource interface from shade servers = conn.compute.servers() # SDK Service/Object Interface response = conn.compute.get('/servers') # REST passthrough ``` -------------------------------- ### Establish Connection from Python Arguments (Optional YAML) (Python) Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/transition_from_profile.rst This Python example demonstrates creating an openstack.connection.Connection object using Python arguments, with the option to fall back to cloud configuration from YAML files or environment variables if a 'cloud' parameter is provided. It's similar to the previous example but allows YAML loading. ```python try: from openstack import config as occ ``` -------------------------------- ### Manage OpenStack Share Group Snapshots Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/shared_file_system.rst Provides functions to list, get, create, reset, update, and delete share group snapshots. A share group snapshot is a point-in-time, read-only copy of data within a share group. Requires an active OpenStack connection and relevant IDs for specific operations. ```python from openstack import connection def list_share_group_snapshots(conn): """List all share group snapshots.""" return conn.shared_file_system.share_group_snapshots() def get_share_group_snapshot(conn, snapshot_id): """Show share group snapshot details.""" return conn.shared_file_system.get_share_group_snapshot(snapshot_id) def share_group_snapshot_members(conn, snapshot_id): """Lists all share group snapshots members.""" return conn.shared_file_system.share_group_snapshot_members(snapshot_id) def create_share_group_snapshot(conn, share_group_id, name=None): """Creates a snapshot from a share group.""" return conn.shared_file_system.create_share_group_snapshot(share_group_id, name=name) def reset_share_group_snapshot_status(conn, snapshot_id, status): """Reset share group snapshot state.""" return conn.shared_file_system.reset_share_group_snapshot_status(snapshot_id, status) def update_share_group_snapshot(conn, snapshot_id, **attrs): """Updates a share group snapshot.""" return conn.shared_file_system.update_share_group_snapshot(snapshot_id, **attrs) def delete_share_group_snapshot(conn, snapshot_id): """Deletes a share group snapshot.""" return conn.shared_file_system.delete_share_group_snapshot(snapshot_id) ``` -------------------------------- ### List OpenStack Compute Images Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/compute.rst Retrieves a list of all available operating system images for creating servers in the OpenStack Compute service. Requires an active connection to the OpenStack cloud. ```python from openstack import connection def list_images(conn): images = conn.compute.images() for image in images: print(image) ``` -------------------------------- ### List OpenStack Network Agents using Python SDK Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/network.rst This example demonstrates listing network agents in OpenStack, such as DHCP, L3, and metering agents. It requires an active connection 'conn' and prints the name and ID of each agent. ```python from openstack import connection def list_network_agents(conn): """List all network agents.""" print("Network Agents:") for agent in conn.network.agents(): print(" %s (%s)" % (agent.name, agent.id)) # Assuming 'conn' is an authenticated OpenStack connection object # list_network_agents(conn) ``` -------------------------------- ### Find DNS Zone using OpenStack SDK Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/dns.rst This example demonstrates how to find a specific DNS zone by its name. It requires a connection object and the zone name, returning the matching zone resource or None. ```python from openstack import connection def find_zone(conn, zone_name): print(f'Finding zone: {zone_name}') zone = conn.dns.find_zone(zone_name) if zone: print(f'Found zone: {zone.id}') else: print('Zone not found.') return zone ``` -------------------------------- ### Creating OpenStack Servers by Image/Flavor Dictionary Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/multi-cloud-demo.rst Shows how to create servers using a dictionary to specify image and flavor identifiers. This approach is useful when the exact type of identifier (name or ID) is known. The example iterates through different cloud configurations and enables debug logging. ```python from openstack import cloud as openstack # Initialize and turn on debug logging openstack.enable_logging(debug=True) for cloud_name, region_name, image, flavor_id in [ ('my-vexxhost', 'ca-ymq-1', 'Ubuntu 16.04.1 LTS [2017-03-03]', '5cf64088-893b-46b5-9bb1-ee020277635d'), ('my-citycloud', 'Buf1', 'Ubuntu 16.04 Xenial Xerus', '0dab10b5-42a2-438e-be7b-505741a7ffcc'), ('my-internap', 'ams01', 'Ubuntu 16.04 LTS (Xenial Xerus)', 'A1.4')]: # Initialize cloud cloud = openstack.connect(cloud=cloud_name, region_name=region_name) # Boot a server, wait for it to boot, and then do whatever is needed # to get a public ip for it. server = cloud.create_server( ``` -------------------------------- ### Run Presentty Documentation Viewer Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/multi-cloud-demo.rst This command uses the 'presentty' tool to render an RST (reStructuredText) file as a presentation. It's a utility for viewing documentation in a slideshow format. Ensure 'presentty' is installed. ```bash presentty doc/source/user/multi-cloud-demo.rst ``` -------------------------------- ### Install virtualenv Tool Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/contributor/setup.rst Installs the virtualenv tool on Debian/Red Hat based systems or other platforms using pip. This tool is used to create isolated Python environments. ```shell $ apt-get install python3-virtualenv # Debian based platforms $ dnf install python3-virtualenv # Red Hat based platforms $ pip install virtualenv # Mac OS X and other platforms ``` -------------------------------- ### List OpenStack Compute Flavors Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/compute.rst Retrieves a list of all available server configurations (flavors) in the OpenStack Compute service. Flavors define resources like disk, memory, and vCPUs. Requires an active connection to the OpenStack cloud. ```python from openstack import connection def list_flavors(conn): flavors = conn.compute.flavors() for flavor in flavors: print(flavor) ``` -------------------------------- ### List OpenStack Security Groups using Python SDK Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/network.rst This example provides code to list all security groups configured in OpenStack. It requires an active connection object 'conn' and iterates through security groups, printing their names and IDs. ```python from openstack import connection def list_security_groups(conn): """List all security groups.""" print("Security Groups:") for security_group in conn.network.security_groups(): print(" %s (%s)" % (security_group.name, security_group.id)) # Assuming 'conn' is an authenticated OpenStack connection object # list_security_groups(conn) ``` -------------------------------- ### Find DNS Recordset using OpenStack SDK Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/dns.rst This example demonstrates how to find a specific DNS recordset by its name and type within a zone. It requires a connection object, zone ID, recordset name, and type, returning the matching recordset or None. ```python from openstack import connection def find_recordset(conn, zone_id, name, record_type='A'): print(f'Finding recordset {name} ({record_type}) in zone {zone_id}') recordset = conn.dns.find_recordset( zone_id=zone_id, name=name, type=record_type ) if recordset: print(f'Found recordset: {recordset.id}') else: print('Recordset not found.') return recordset ``` -------------------------------- ### Password-based Authentication Examples (Project, Domain, Trust, System Scoped) Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/config/configuration.rst Demonstrates password-based authentication configurations for OpenStack projects, including project-scoped, domain-scoped, trust-scoped, and system-scoped authentication. ```yaml example: auth: auth_url: http://example.com/identity password: password project_domain_id: default project_name: admin user_domain_id: default username: admin region_name: RegionOne ``` ```yaml example: auth: auth_url: http://example.com/identity domain_id: default password: password username: admin region_name: RegionOne ``` ```yaml example-trust: auth: auth_url: http://example.com/identity password: password username: admin trust_id: 95946f9eef864fdc993079d8fe3e5747 region_name: RegionOne ``` ```yaml example-system: auth: auth_url: http://example.com/identity password: password system_scope: all username: admin region_name: RegionOne ``` -------------------------------- ### YAML Configuration for OpenStack Cloud Source: https://github.com/openstack/openstacksdk/blob/master/README.rst Example of a `clouds.yaml` file used by openstacksdk for cloud provider configuration. It specifies authentication details and region names. This file is typically provided by the cloud provider or deployment tooling. ```yaml clouds: mordred: region_name: Dallas auth: username: 'mordred' password: XXXXXXX project_name: 'demo' auth_url: 'https://identity.example.com' ``` -------------------------------- ### Establish Connection from Named Cloud Configuration (Python) Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/transition_from_profile.rst This example demonstrates how to create an openstack.connection.Connection object using parameters defined in a clouds.yaml file or environment variables. It utilizes the `from_config` method with a specified cloud name. ```python import openstack.connection conn = connection.from_config(cloud_name='name-of-cloud-you-want') ``` -------------------------------- ### List OpenStack Compute Servers Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/compute.rst Retrieves a list of all available servers (virtual machines) within the OpenStack Compute service. Requires an active connection to the OpenStack cloud. ```python from openstack import connection def list_servers(conn): servers = conn.compute.servers() for server in servers: print(server) ``` -------------------------------- ### List OpenStack Subnets using Python SDK Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/network.rst This example shows how to retrieve and display a list of all subnets within the OpenStack environment. It requires a valid OpenStack connection object 'conn'. The function iterates through subnets and prints their names and IDs. ```python from openstack import connection def list_subnets(conn): """List all subnets.""" print("Subnets:") for subnet in conn.network.subnets(): print(" %s (%s)" % (subnet.name, subnet.id)) # Assuming 'conn' is an authenticated OpenStack connection object # list_subnets(conn) ``` -------------------------------- ### YAML Configuration Precedence Example Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/config/configuration.rst Illustrates how project name and ID are specified multiple times in clouds.yaml, showing that higher-level and name-based configurations take precedence. ```yaml clouds: mtvexx: profile: https://vexxhost.com auth: username: mordred@inaugust.com password: XXXXXXXXX project_name: mylessfavoriteproject project_id: 0bedab75-898c-4521-a038-0b4b71c41bed region_name: ca-ymq-1 project_name: myfavoriteproject project_id: 2acf9403-25e8-479e-a3c6-d67540c424a4 ``` -------------------------------- ### List OpenStack Networks Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/compute.rst Retrieves a list of all available networks in the OpenStack cloud, which can be used for server connectivity. Requires an active connection to the OpenStack cloud. ```python from openstack import connection def list_networks(conn): networks = conn.network.networks() for network in networks: print(network) ``` -------------------------------- ### Manage OpenStack Shares Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/shared_file_system.rst Provides functions to manage (create or update) and unmanage shares within the OpenStack Shared File System service. Requires an active OpenStack connection and appropriate parameters for share operations. ```python from openstack import connection def manage_share(conn, share_id, driver_options=None, **kwargs): """Manage a share with Manila.""" return conn.shared_file_system.manage_share(share_id, driver_options=driver_options, **kwargs) def unmanage_share(conn, share_id): """Unmanage a share from Manila.""" return conn.shared_file_system.unmanage_share(share_id) ``` -------------------------------- ### Configure Logging to File and Console Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/logging.rst This example demonstrates how to configure openstacksdk logging to write messages to both a file named 'openstack.log' and the console's standard output. It also enables debug level logging. ```python import sys import openstack openstack.enable_logging( debug=True, path='openstack.log', stream=sys.stdout) ``` -------------------------------- ### Manage OpenStack Share Instances Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/shared_file_system.rst Provides functionality to list, show, reset status, and force-delete share instances within the Shared File System service. Requires an active OpenStack connection and a share instance ID for specific operations. ```python from openstack import connection def share_instances(conn): """List share instances.""" return conn.shared_file_system.share_instances() def get_share_instance(conn, instance_id): """Show details for a single share instance.""" return conn.shared_file_system.get_share_instance(instance_id) def reset_share_instance_status(conn, instance_id, status): """Explicitly updates the state of a share instance.""" return conn.shared_file_system.reset_share_instance_status(instance_id, status) def delete_share_instance(conn, instance_id): """Force-deletes a share instance.""" return conn.shared_file_system.delete_share_instance(instance_id) ``` -------------------------------- ### List OpenStack Networks using Python SDK Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/network.rst This snippet demonstrates how to list all networks available in the OpenStack cloud. It requires an active OpenStack connection object 'conn'. The output is a list of network resources. ```python from openstack import connection def list_networks(conn): """List all networks.""" print("Networks:") for network in conn.network.networks(): print(" %s (%s)" % (network.name, network.id)) # Assuming 'conn' is an authenticated OpenStack connection object # list_networks(conn) ``` -------------------------------- ### Create OpenStack Key Pair Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/compute.rst Creates a new key pair (public and private key) for secure server access in the OpenStack Compute service. This is essential for logging into newly created servers. Requires an active connection to the OpenStack cloud. ```python from openstack import connection def create_keypair(conn, key_name): keypair = conn.compute.create_keypair(name=key_name) print(keypair) return keypair ``` -------------------------------- ### Normalize Image Data Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/multi-cloud-demo.rst Connects to an OpenStack cloud and retrieves image information, then pretty-prints the normalized image data. This example demonstrates basic cloud connection and image retrieval. ```python from openstack import cloud as openstack openstack.enable_logging() cloud = openstack.connect(cloud='fuga', region_name='cystack') image = cloud.get_image( 'Ubuntu 16.04 LTS - Xenial Xerus - 64-bit - Fuga Cloud Based Image') cloud.pprint(image) ``` -------------------------------- ### Create OpenStack Connection using Python Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/connect.rst Demonstrates how to create a connection instance to an OpenStack cloud using the openstack.connect factory function. This requires providing connection parameters such as authentication credentials and cloud endpoint details. The resulting connection object is used to interact with OpenStack services. ```python from openstack import connect def create_connection(): """First create a connection to your OpenStack cloud. The connect() function has a number of arguments that you can use to specify how to authenticate to your cloud. For example: .. code-block:: python conn = connect(auth_url='http://...', user_domain_name='...', username='...', password='...', project_domain_name='...', project_name='...') :return: An openstack.connection.Connection object """ # This is an example of how to create a connection, you will likely # want to provide your own arguments to connect() # see https://docs.openstack.org/openstacksdk/latest/user/connect.html # for more information. conn = connect() return conn if __name__ == '__main__': connection = create_connection() # You can now use the connection object to interact with OpenStack services print("Connection created successfully.") # Example: List servers (uncomment to run) # servers = list(connection.compute.servers()) # print(f"Found {len(servers)} servers.") connection.close() print("Connection closed.") ``` -------------------------------- ### OpenStack Functional Test clouds.yaml Configuration Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/contributor/testing.rst Example minimal configuration for a clouds.yaml file to connect functional tests to a DevStack instance. This file specifies cloud accounts, flavor, and image names required for testing. ```yaml clouds: devstack-admin: auth: project_name: "admin" username: "admin" password: "stackuser" user_domain_name: "Default" project_domain_name: "Default" region_name: "regionOne" identity_api_version: 3 devstack: auth: project_name: "demo" username: "demo" password: "stackuser" user_domain_name: "Default" project_domain_name: "Default" region_name: "regionOne" identity_api_version: 3 devstack-demo: auth: project_name: "demo2" username: "demo2" password: "stackuser" user_domain_name: "Default" project_domain_name: "Default" region_name: "regionOne" identity_api_version: 3 functional: flavor_name: "m1.tiny" image_name: "tiny" ``` -------------------------------- ### List OpenStack Ports using Python SDK Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/network.rst This code snippet illustrates how to fetch and display all network ports in your OpenStack deployment. It utilizes an existing OpenStack connection 'conn' and prints the name and ID for each port found. ```python from openstack import connection def list_ports(conn): """List all ports.""" print("Ports:") for port in conn.network.ports(): print(" %s (%s)" % (port.name, port.id)) # Assuming 'conn' is an authenticated OpenStack connection object # list_ports(conn) ``` -------------------------------- ### Proxy Method for Listing Resources Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/contributor/layout.rst Shows an example of a method within a service's Proxy class that utilizes a Resource's list method. This provides a higher-level interface for users to interact with services, abstracting away the direct use of Resource objects and Adapters. ```python from openstack.compute.v2 import flavor def list_flavors(self, **params): return flavor.Flavor.list(self.session, **params) ``` -------------------------------- ### Munch Dict-Object Example Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/multi-cloud-demo.rst Illustrates how to use Munch objects, which behave as both dictionaries and objects, for accessing image attributes. It connects to an OpenStack cloud and retrieves an image, printing its name using both dictionary and object access methods. ```python from openstack import cloud as openstack openstack.enable_logging(debug=True) cloud = openstack.connect(cloud='zetta', region_name='no-osl1') image = cloud.get_image('Ubuntu 14.04 (AMD64) [Local Storage]') print(image.name) print(image['name']) ``` -------------------------------- ### List OpenStack Routers using Python SDK Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/network.rst This snippet shows how to list all routers available in the OpenStack cloud. It uses an established connection object 'conn' to retrieve router details and print their names and IDs. ```python from openstack import connection def list_routers(conn): """List all routers.""" print("Routers:") for router in conn.network.routers(): print(" %s (%s)" % (router.name, router.id)) # Assuming 'conn' is an authenticated OpenStack connection object # list_routers(conn) ``` -------------------------------- ### List OpenStack Shared File System Availability Zones Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/shared_file_system.rst Lists availability zones for the Shared File System service. Availability zones are failure domains for shared file systems. This function requires an active OpenStack connection object. ```python from openstack import connection def list_availability_zones(conn): """List availability zones for the Shared File System service.""" return conn.shared_file_system.availability_zones() ``` -------------------------------- ### Utilities - Building Config Drives Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/proxies/baremetal.rst Information on utilities for building config drives for baremetal provisioning. ```APIDOC ## Utilities - Building Config Drives ### Description This section provides information and utilities for building config drives used in baremetal provisioning. ### Module `openstack.baremetal.configdrive` ### Usage Refer to the module's members for specific functions and classes related to config drive creation. ``` -------------------------------- ### Get Node in OpenStack Clustering Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/clustering/node.rst This function retrieves a specific node by its name or ID from the OpenStack clustering service. It takes the connection object and the node's identifier as arguments. This is part of the openstacksdk's clustering examples. ```python def get_node(conn): """Get a node.""" node_id = "node-id-or-name" node = conn.clustering.get_node(node_id) print("Get Node:") print(node) ``` -------------------------------- ### OpenStackSDK Multi-Cloud Initialization and Resource Management Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/multi-cloud-demo.rst This Python script demonstrates initializing connections to multiple OpenStack clouds and regions using OpenStackSDK. It includes examples of enabling debug logging, creating an image, finding a suitable server flavor based on RAM, and booting a server with automatic IP assignment. The script relies on the 'openstacksdk' library and requires a properly configured 'clouds.yaml' file. ```python from openstack import cloud as openstack # Initialize and turn on debug logging openstack.enable_logging(debug=True) for cloud_name, region_name in [ ('my-vexxhost', 'ca-ymq-1'), ('my-citycloud', 'Buf1'), ('my-internap', 'ams01'), ]: # Initialize cloud cloud = openstack.connect(cloud=cloud_name, region_name=region_name) # Upload an image to the cloud image = cloud.create_image( 'devuan-jessie', filename='devuan-jessie.qcow2', wait=True, ) # Find a flavor with at least 512M of RAM flavor = cloud.get_flavor_by_ram(512) # Boot a server, wait for it to boot, and then do whatever is needed # to get a public ip for it. cloud.create_server( 'my-server', image=image, flavor=flavor, wait=True, auto_ip=True, ) ``` -------------------------------- ### Python Indentation: Continuation Line at Block Start Source: https://github.com/openstack/openstacksdk/blob/master/HACKING.rst This code example illustrates the recommended Python indentation for continuation lines when breaking the first line of a block, such as a for loop. It involves an additional 4-space indent for the continuation line. ```python for val in self.some_method( arg1, arg1, arg3, arg4 ): self.do_something_awesome() ``` -------------------------------- ### Define Fake Resource Service (Python) Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/contributor/create/resource.rst This snippet defines the FakeService class, which specifies the valid versions and the service catalog name for the 'Fake' service. It's used by resources to construct appropriate URLs. This example assumes it's part of the 'openstack.fake' namespace. ```Python from openstack.service import Service class FakeService(Service): name = "fake" version = "1.0" # other attributes like catalog_type, endpoint_override, etc. pass ``` -------------------------------- ### Build Project Documentation Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/contributor/setup.rst Builds the project's documentation, which is written in reStructured Text and uses Sphinx. The 'docs' command is defined in 'tox.ini' and generates HTML output located in 'docs/build/html'. ```shell (sdk3)$ tox -e docs ``` -------------------------------- ### List Profiles using openstacksdk Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/clustering/profile.rst This Python function demonstrates how to list profiles using the openstacksdk. It supports sorting options via the 'sort' parameter and pagination using 'limit' and 'marker'. Ensure the openstacksdk is installed and configured to interact with your OpenStack environment. ```python def list_profiles(conn): ``` -------------------------------- ### Creating OpenStack Servers by Name or ID Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/multi-cloud-demo.rst Shows how to create servers in different OpenStack clouds by specifying image and flavor using their names or IDs. This example also demonstrates enabling debug logging and iterating through various cloud configurations. It requires cloud details, image identifiers, and flavor identifiers. ```python from openstack import cloud as openstack # Initialize and turn on debug logging openstack.enable_logging(debug=True) for cloud_name, region_name, image, flavor in [ ('my-vexxhost', 'ca-ymq-1', 'Ubuntu 16.04.1 LTS [2017-03-03]', 'v1-standard-4'), ('my-citycloud', 'Buf1', 'Ubuntu 16.04 Xenial Xerus', '4C-4GB-100GB'), ('my-internap', 'ams01', 'Ubuntu 16.04 LTS (Xenial Xerus)', 'A1.4')]: # Initialize cloud cloud = openstack.connect(cloud=cloud_name, region_name=region_name) # Boot a server, wait for it to boot, and then do whatever is needed # to get a public ip for it. server = cloud.create_server( 'my-server', image=image, flavor=flavor, wait=True, auto_ip=True) print(server.name) print(server['name']) cloud.pprint(server) # Delete it - this is a demo cloud.delete_server(server, wait=True, delete_ips=True) ``` -------------------------------- ### Manage OpenStack Share Metadata Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/shared_file_system.rst Enables listing all metadata for a share, retrieving a specific metadata item by key, creating new metadata, updating existing metadata, and deleting metadata items. Requires an active OpenStack connection and share ID. ```python from openstack import connection def list_share_metadata(conn, share_id): """Lists all metadata for a given share.""" return conn.shared_file_system.share_metadata(share_id) def get_share_metadata_item(conn, share_id, key): """Retrieves a specific metadata item from a shares metadata by its key.""" return conn.shared_file_system.get_share_metadata_item(share_id, key) def create_share_metadata(conn, share_id, metadata): """Creates share metadata.""" return conn.shared_file_system.create_share_metadata(share_id, metadata) def update_share_metadata(conn, share_id, metadata): """Updates metadata of a given share.""" return conn.shared_file_system.update_share_metadata(share_id, metadata) def delete_share_metadata(conn, share_id, keys): """Deletes a specific metadata item from a shares metadata by its key. Can specify multiple keys to be deleted.""" return conn.shared_file_system.delete_share_metadata(share_id, keys=keys) ``` -------------------------------- ### Server Information Retrieval Options Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/multi-cloud-demo.rst Demonstrates creating a server and then retrieving its information using different options: default (detailed=True), detailed=False, and bare=True. It shows how to control the level of detail in the returned server object. ```python from openstack import cloud as openstack openstack.enable_logging(debug=True) cloud = openstack.connect(cloud='my-citycloud', region_name='Buf1') try: server = cloud.create_server( 'my-server', image='Ubuntu 16.04 Xenial Xerus', flavor=dict(id='0dab10b5-42a2-438e-be7b-505741a7ffcc'), wait=True, auto_ip=True) print("\n\nFull Server\n\n") cloud.pprint(server) print("\n\nTurn Detailed Off\n\n") cloud.pprint(cloud.get_server('my-server', detailed=False)) print("\n\nBare Server\n\n") cloud.pprint(cloud.get_server('my-server', bare=True)) finally: # Delete it - this is a demo cloud.delete_server(server, wait=True, delete_ips=True) ``` -------------------------------- ### Delete DNS Recordset using OpenStack SDK Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/dns.rst This example demonstrates how to delete a DNS recordset. It requires a connection object, zone ID, and recordset ID, removing the specified recordset. ```python from openstack import connection def delete_recordset(conn, zone_id, recordset_id): print(f'Deleting recordset {recordset_id} from zone {zone_id}') conn.dns.delete_recordset(zone_id, recordset_id) print(f'Recordset {recordset_id} deleted.') ``` -------------------------------- ### Delete DNS Zone using OpenStack SDK Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/dns.rst This example demonstrates how to delete a DNS zone. It requires a connection object and the zone ID, removing the specified zone from your OpenStack cloud. ```python from openstack import connection def delete_zone(conn, zone_id): print(f'Deleting zone: {zone_id}') conn.dns.delete_zone(zone_id) print(f'Zone {zone_id} deleted.') ``` -------------------------------- ### Delete OpenStack Network and Subnets using Python SDK Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/network.rst This example demonstrates how to delete a project network and all its associated subnets. It requires an active OpenStack connection object 'conn' and the ID of the network to be deleted. ```python from openstack import connection def delete_network(conn, network_id): """Delete a project network and its subnets.""" conn.network.delete_network(network_id) print(f"Deleted network {network_id}") # Assuming 'conn' is an authenticated OpenStack connection object # and 'network_to_delete_id' is the ID of the network to be deleted # delete_network(conn, network_to_delete_id) ``` -------------------------------- ### Python: Create Image and Server using OpenStack SDK Cloud Layer Source: https://github.com/openstack/openstacksdk/blob/master/README.rst Demonstrates using the OpenStack SDK's cloud layer to perform multiple operations: uploading an image, finding a flavor by RAM, and booting a server with automatic IP assignment. It includes `wait=True` to ensure operations complete before proceeding. ```python import openstack # Initialize and turn on debug logging openstack.enable_logging(debug=True) # Initialize connection conn = openstack.connect(cloud='mordred') # Upload an image to the cloud image = conn.create_image( 'ubuntu-trusty', filename='ubuntu-trusty.qcow2', wait=True) # Find a flavor with at least 512M of RAM flavor = conn.get_flavor_by_ram(512) # Boot a server, wait for it to boot, and then do whatever is needed # to get a public IP address for it. conn.create_server( 'my-server', image=image, flavor=flavor, wait=True, auto_ip=True) ``` -------------------------------- ### Python: Initialize OpenStack Connection and Manage Resources Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/multi-cloud-demo.rst Python code to initialize OpenStack connections to multiple clouds and regions, create an image, find a flavor, and boot a server. It demonstrates enabling debug logging for verbose output. ```python from openstack import cloud as openstack # Initialize and turn on debug logging openstack.enable_logging(debug=True) for cloud_name, region_name in [ ('my-vexxhost', 'ca-ymq-1'), ('my-citycloud', 'Buf1'), ('my-internap', 'ams01')]: # Initialize cloud cloud = openstack.connect(cloud=cloud_name, region_name=region_name) # Upload an image to the cloud image = cloud.create_image( 'devuan-jessie', filename='devuan-jessie.qcow2', wait=True) # Find a flavor with at least 512M of RAM flavor = cloud.get_flavor_by_ram(512) # Boot a server, wait for it to boot, and then do whatever is needed # to get a public ip for it. cloud.create_server( 'my-server', image=image, flavor=flavor, wait=True, auto_ip=True) ``` -------------------------------- ### OpenStack Service Conditional Override Example (Python) Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/multi-cloud-demo.rst Shows a Python code snippet that uses an OpenStack connection, implying that service conditionals might be configured elsewhere (e.g., YAML). This example focuses on checking service availability after potential overrides. Requires an OpenStack connection. ```python from openstack import cloud as openstack openstack.enable_logging(debug=True) cloud = openstack.connect(cloud='rax', region_name='DFW') print(cloud.has_service('network')) ``` -------------------------------- ### OpenStack Authentication and Connection Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/transition_from_profile.rst Demonstrates how to configure and establish a connection to an OpenStack cloud using various authentication methods. ```APIDOC ## OpenStack Authentication and Connection ### Description This section describes how to configure and establish a connection to an OpenStack cloud. It covers the parameters for `get_one_cloud` and how to use them for authentication and connection customization. ### Method N/A (Configuration and Instantiation) ### Endpoint N/A ### Parameters #### `openstack.config.loader.OpenStackConfig.get_one_cloud` Parameters - **region_name** (string) - Required - The name of the cloud region to connect to. - **auth_type** (string) - Required - Specifies the authentication plugin to use (e.g., 'password'). - **auth** (dict) - Required - A dictionary containing parameters required by the auth plugin. Common parameters include: - **auth_url** (string) - The URL of the authentication service. - **username** (string) - The username for authentication. - **user_domain_name** (string) - The domain name for the user. - **project_name** (string) - The project name for authentication. - **user_project_name** (string) - An alternative project name specification. - **password** (string) - The user's password. - **[service_type]_endpoint_override** (string) - Optional - Overrides the endpoint for a specific service (e.g., `compute_endpoint_override`). ### Request Example ```python from os_client_config import config as occ from openstack import connection loader = occ.OpenStackConfig( app_name='spectacular-app', app_version='1.0' ) cloud_region = loader.get_one_cloud( region_name='my-awesome-region', auth_type='password', auth=dict( auth_url='https://auth.example.com', username='amazing-user', user_domain_name='example-domain', project_name='astounding-project', user_project_name='example-domain', password='super-secret-password', ) ) conn = connection.from_config(cloud_config=cloud_region) ``` ### Response #### Success Response (Connection Object) - **conn** (`openstack.connection.Connection`) - An active connection object to the specified OpenStack region. #### Response Example ```python # The 'conn' object is now available for interacting with OpenStack services. print(conn.current_project_id) ``` ### Error Handling - **ImportError**: If `os_client_config` is not installed, an `ImportError` will occur, and the code will attempt to use a fallback mechanism. - **Authentication/Connection Errors**: Specific errors related to authentication failures or network issues will be raised by the `openstack-sdk` library. ``` -------------------------------- ### Resource Action Mappings in openstacksdk Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/contributor/create/resource.rst This snippet illustrates the mapping between resource actions and their corresponding attributes in the openstacksdk. It shows how methods like head, list, fetch, and commit are enabled by specific boolean attributes. ```text | :class:`~openstack.resource.Resource.head` | allow_head | +----------------------------------------------+----------------+ | :class:`~openstack.resource.Resource.list` | allow_list | +----------------------------------------------+----------------+ | :class:`~openstack.resource.Resource.fetch` | allow_fetch | +----------------------------------------------+----------------+ | :class:`~openstack.resource.Resource.commit` | allow_commit | ``` -------------------------------- ### Open Port (Add Security Group Rule) using Python SDK Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/network.rst This example demonstrates how to add a security group rule to allow specific inbound traffic, such as HTTPS on port 443. It requires an OpenStack connection 'conn', the security group ID, and defines the rule parameters. ```python from openstack import connection def open_port(conn, security_group_id): """Open a port for a security group.""" rule = conn.network.create_security_group_rule( security_group_id=security_group_id, direction='ingress', ethertype='IPv4', protocol='tcp', port_range_min=443, port_range_max=443 ) print(f"Opened port 443 for security group {security_group_id}") return rule # Assuming 'conn' is an authenticated OpenStack connection object # and 'my_security_group_id' is the ID of an existing security group # open_port(conn, my_security_group_id) ``` -------------------------------- ### Create OpenStack Server Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/compute.rst Creates a new virtual machine (server) in the OpenStack Compute service. Requires specifying a name, image, flavor, and network. Optionally, a key pair can be provided for secure access. The function waits for the server to become active. Requires an active connection to the OpenStack cloud. ```python from openstack import connection def create_server(conn, name, image_id, flavor_id, network_id, key_name=None): server_create_args = { 'name': name, 'image_id': image_id, 'flavor_id': flavor_id, 'networks': [{'uuid': network_id}], } if key_name: server_create_args['key_name'] = key_name server = conn.compute.create_server(**server_create_args) print(f"Waiting for server '{name}' to become active...") server = conn.compute.wait_for_server(server) print(server) return server ``` -------------------------------- ### Get Object Data Source: https://github.com/openstack/openstacksdk/blob/master/doc/source/user/guides/object_store.rst Retrieves the data content of a specific object. ```APIDOC ## GET /objects/{object_name}/data ### Description Retrieves the data content of a specific object within a container. ### Method GET ### Endpoint /objects/{object_name}/data ### Parameters #### Path Parameters - **object_name** (string) - Required - The name of the object to retrieve data for. - **container_name** (string) - Required - The name of the container the object resides in. ### Request Example ```python ob = conn.object_store.get_object("my_container", "my_object.txt") data = conn.object_store.get_object_data(ob) ``` ### Response #### Success Response (200) - **data** (bytes) - The binary content of the object. #### Response Example ``` Hello, world! ``` ```