### Extension.py with Setup and Settings Registration Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/platform_developers/create_server_extension.html Example `extension.py` file demonstrating how to register server slices and environment settings. ```python # File: extension.py from inmanta.server.extensions import ApplicationContext from inmanta import data def setup(application: ApplicationContext) -> None: application.register_slice() def register_environment_settings(application: ApplicationContext) -> None: application.register_environment_setting( data.Setting( name="my_environment_setting", default=False, typ="bool", validator=data.convert_boolean, doc="Explain what the setting does.", ) ) ``` -------------------------------- ### Setup Python Virtual Environment and Install Inmanta Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/lsm/quickstart/quickstart.html Prepare your development environment by creating a Python virtual environment and installing the Inmanta package. Ensure Python 3.13 is installed. ```bash $ mkdir -p ~/.virtualenvs $ python3 -m venv ~/.virtualenvs/lsm-srlinux $ source ~/.virtualenvs/lsm-srlinux/bin/activate $ pip install inmanta ``` -------------------------------- ### Setup Virtual Environment for Testing Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/reference/modules/n5k_lan/docs/development.html Set up a Python virtual environment and install necessary dependencies for testing. Configure environment variables for Inmanta test setup, including the module repository and optional Netconf timeout. ```bash mkvirtualenv inmanta-test -p python3 pip install -r requirements.dev.txt pip install -r requirements.txt mkdir /tmp/env export INMANTA_TEST_ENV=/tmp/env export INMANTA_MODULE_REPO=git@github.com:inmanta/ # Optional value to set in environments with large config files. 60 seconds is used if not specified. export N5K_NETCONF_TIMEOUT="60" ``` -------------------------------- ### Setup Virtual Environment for Testing Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/reference/modules/gcp_interco/README.html Steps to set up a virtual environment and install dependencies for testing the GCP Interco module. ```bash virtualenv inmanta-test -p python3 source inmanta-test/bin/activate pip install -r requirements.dev.txt pip install -r requirements.txt ``` -------------------------------- ### Install PostgreSQL 16 Server on RHEL 9 Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/install/2-install-postgresql-orchestrator.html Installs the PostgreSQL 16 server package and enables the service to start on boot. ```bash sudo dnf module install postgresql:16/server sudo systemctl enable postgresql ``` -------------------------------- ### Set up virtual environment and install module Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/reference/modules/dzs/README.html Use these commands to create a virtual environment and install the module with its development dependencies. The first command assumes virtualenvwrapper is installed. ```bash mkvirtualenv inmanta-test -p python3 -a . pip install -e . -c requirements.txt -r requirements.dev.txt ``` -------------------------------- ### Navigate to LSM SR Linux Example Directory Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/lsm/quickstart/quickstart.html Change your current directory to the LSM SR Linux example folder within the Inmanta examples repository. ```bash $ cd examples/lsm-srlinux ``` -------------------------------- ### Install Inmanta Agent via Cloud-Init Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/reference/modules/openstack/README.html A bash script to be used with the `user_data` attribute for cloud-init. It installs the Inmanta agent from RPM, configures it, and starts the service. Ensure the `env_id`, `port`, and `env_server` variables are correctly substituted. ```bash #!/bin/bash hostname {{ name }} curl -1sLf \ 'https://packages.inmanta.com/public/oss-stable/setup.rpm.sh' \ | sudo -E bash dnf install -y inmanta-oss-agent cat > /etc/inmanta/agent.cfg < dict[NormalizedName, packaging.version.Version]: """ Return a list of all installed packages in the site-packages of a python interpreter. :param only_editable: List only packages installed in editable mode. :return: A dict with package names as keys and versions as values """ cmd = PipCommandBuilder.compose_list_command(self.python_path, format=PipListFormat.json, only_editable=only_editable) output = CommandRunner(LOGGER_PIP).run_command_and_log_output(cmd, stderr=subprocess.DEVNULL, env=os.environ.copy()) return {canonicalize_name(r["name"]): packaging.version.Version(r["version"]) for r in json.loads(output)} ``` -------------------------------- ### Complete project.yml Example Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/reference/projectyml.html This example demonstrates a full project.yml configuration, including metadata, module requirements, repository definitions, pip settings, and environment configurations. ```yaml name: quickstart description: A quickstart project that installs a drupal website. author: Inmanta author_email: code@inmanta.com license: Apache 2.0 copyright: Inmanta (2021) modulepath: libs downloadpath: libs install_mode: release repo: - url: https://github.com/inmanta/ type: git requires: - apache ~= 0.5.2 - drupal ~= 0.7.3 - exec ~= 1.1.4 - ip ~= 1.2.1 - mysql ~= 0.6.2 - net ~= 1.0.5 - php ~= 0.3.1 - redhat ~= 0.9.2 - std ~= 3.0.2 - web ~= 0.3.3 - yum ~= 0.6.2 freeze_recursive: true freeze_operator: ~= pip: index-url: https://pypi.org/simple/ extra-index-url: [] pre: false use-system-config: false environment_settings: auto_deploy: true server_compile: true ``` -------------------------------- ### Get Installed Python Packages Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/env.html Returns a dictionary of installed packages and their versions. Optionally filters to include only packages installed in editable mode. ```python def get_installed_packages(self, only_editable: bool = False) -> dict[NormalizedName, packaging.version.Version]: """ Return a list of all installed packages in the site-packages of a python interpreter. :param only_editable: List only packages installed in editable mode. :return: A dict with package names as keys and versions as values """ if self.is_using_virtual_env() and not only_editable: return PythonWorkingSet.get_packages_in_working_set() return super().get_installed_packages(only_editable=only_editable) ``` -------------------------------- ### Configure n5k_lan Device and Resources Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/reference/modules/n5k_lan/README.html Example demonstrating how to instantiate a n5k_lan device, define credentials using environment variables, and configure VLAN priority and spanning tree settings. ```python import n5k_lan switch = n5k_lan::Device( host="myrouter", credentials=n5k_lan::Credentials( username_env_var="N5K_USER", password_env_var="N5K_PASS", ), schema_file = "./nx-osv.yaml", ) resource = n5k_lan::Resource( name="n5k", device=switch ) designated_priority = n5k_lan::DesignatedVlanPriority(priority=8192) vlan = n5k_lan::Vlan( resource=resource, vlan={vlan}, purged=false, designated_priority=designated_priority ) spanning_tree = n5k_lan::SpanningTree(resource=resource) spanning_tree.vlan_designated_priority += designated_priority ``` -------------------------------- ### Get Reports (since start) Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/reference/swagger.html Retrieves compile reports that were generated after a specified start time. ```APIDOC ## GET /api/v1/compilereport ### Description Return compile reports newer then start. ### Method GET ### Endpoint /api/v1/compilereport ### Parameters #### Query Parameters - **start** (string) - Required - The timestamp to filter reports from. ``` -------------------------------- ### Get Installed Versions Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/data/schema.html Retrieves the set of installed schema versions from the schemamanager table. Raises TableNotFound if the table does not exist. ```python async def get_installed_versions(self) -> set[int]: """ Returns the set of all versions that have been installed. :raises TableNotFound: """ versions: Optional[Record] = None try: versions = await self.connection.fetchrow( f"select installed_versions from {SCHEMA_VERSION_TABLE} where name=$1", self.name ) except UndefinedTableError as e: raise TableNotFound() from e if versions is None or versions["installed_versions"] is None: return set() return set(versions["installed_versions"]) ``` -------------------------------- ### Basic Client Initialization and Environment Listing Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/reference/python_client.html Demonstrates how to initialize the Python client and retrieve a list of environments with details. ```APIDOC ## Basic Client Initialization and Environment Listing ### Description Initialize the Inmanta Service Orchestrator client and fetch a list of environments, including detailed information. ### Method `environment_list` ### Parameters - `details` (bool) - Optional - If True, returns detailed information about each environment. ### Request Example ```python client = inmanta.protocol.endpoints.Client(name="api", timeout=120) result = await client.environment_list(details=True) assert result.code == 200 for key, value in result.result["data"].items(): ... ``` ### Response #### Success Response (200) - `result` (dict) - Contains the list of environments and their details. #### Response Example ```json { "code": 200, "result": { "data": { "env1_id": { "name": "environment1", "id": "env1_id" }, "env2_id": { "name": "environment2", "id": "env2_id" } } } } ``` ``` -------------------------------- ### Navigate to SR Linux examples directory Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/quickstart.html Changes the current directory to the SR Linux examples folder. This is where project configuration files are located. ```bash cd examples/Networking/SR\ Linux/ ``` -------------------------------- ### Get Installed Module Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/module.html Retrieves an installed module object based on the project and module name. It first determines the module's path. ```python def get_installed_module(self, project: Optional["Project"], module_name: str) -> Optional[TModule]: """ Returns a module object for a module if it is installed. :param project: The project associated with the module. :param module_name: The name of the module. """ path: Optional[str] = self.path_for(module_name) ``` -------------------------------- ### Get Inmanta Package Requirements Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/env.html Retrieves the content of a requirement file to be supplied to pip install invocations. This ensures that no Inmanta packages are overridden during installations. ```python protected_inmanta_packages: list[str] = cls.get_protected_inmanta_packages() workingset: dict[NormalizedName, packaging.version.Version] = PythonWorkingSet.get_packages_in_working_set() return [ ``` -------------------------------- ### Deploy Checkpoint Hosts and Rules Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/reference/modules/checkpoint/README.html Example demonstrating the deployment of two checkpoint hosts, a TCP service, and a rule to drop traffic between them. Requires setting up credentials and defining host/service objects. ```inmanta import checkpoint credentials = checkpoint::Credentials( host="6.6.6.6", username_env_var="MY_USER_ENV_VAR", password_env_var="MY_PASS_ENV_VAR", ) host1 = checkpoint::Host( ip_address="1.1.1.1", name="test_host1", security_groups=[], credentials=credentials, ) host2 = checkpoint::Host( ip_address="2.2.2.2", name="test_host2", security_groups=[], credentials=credentials, ) service = checkpoint::TCPService( name="https", port=443, credentials=credentials, ) rule = checkpoint::Rule( name="test_rule", layer="vsx-gw-1_p Network", position="top", position_reference_object="inmanta", source=[host1], destination=[host2], action = "Drop", services=[service], credentials=credentials, purged=false, ) checkpoint::PolicyInstallV3( policy_package = "vsx-gw-1_p", targets = ["vsx-gw-1"], credentials=credentials, overwrite = true, ) ``` -------------------------------- ### Get Installed Python Packages Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/env.html Retrieves a dictionary of installed Python package names and their versions from the current working set. It can optionally filter to include only Inmanta modules. ```python return { name: packaging.version.Version(dist_info.version) for name, dist_info in cls.get_dist_in_working_set().items() if not inmanta_modules_only or name.startswith(const.MODULE_PKG_NAME_PREFIX) } ``` -------------------------------- ### Start Inmanta Server (Container) Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/administrators/upgrading_the_orchestrator.html Reload the systemd user daemon and start the new Inmanta orchestrator service for container-based installations. Database migrations may occur during startup. ```bash systemctl --user daemon-reload systemctl --user start inmanta-server.service ``` -------------------------------- ### Get Installed Distributions Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/env.html Retrieves all installed Python distributions from the current sys.path. Returns a dictionary mapping canonicalized package names to their distribution info. Ensures the first entry for each name is returned. ```python return { packaging.utils.canonicalize_name(dist_info.name): dist_info for dist_info in reversed(list(distributions())) # make sure we get the first entry for every name } ``` -------------------------------- ### Create Network and Host Instances Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/model_developers/resource_sets.html Demonstrates the creation of network and host instances. This includes creating a single network with one host and then creating multiple networks with multiple hosts each. ```inmanta # create network 0 with only one host Host(network=Network(id=0), id=0) # create 999 networks with 5 hosts each for i in std::sequence(999, start=1): network = Network(id=i) for j in std::sequence(5): Host(network=network, id=j) end end ``` -------------------------------- ### Deploy VM from Template using vcenter adapter Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/reference/modules/vcenter/README.html This example demonstrates how to deploy a virtual machine from an existing template on vCenter using the Inmanta vcenter adapter. It configures connection details, data center, and the virtual machine with specific hardware and network settings. ```inmanta import vcenter vc = vcenter::VCenter( name="My Vcenter", host="vcenter.example.com", port=443, credentials=vcenter::Credentials( username_env_variable="VCENTER_USER", password_env_variable="VCENTER_PASSWORD" ), ) dc = vcenter::DataCenter( parent=vc.root, name="mydc" ) vm = vcenter::VirtualMachineFromTemplate( parent=dc.vm, name="test_virtual_machine", template_path="/mydc/vm/CentOS7Template", datastore_path="/mydc/datastore/DatastoreCluster/datastore1", resource_pool_path="/mydc/host/lab/Resources", memory_mb=2048, cpu_num=2, cpu_num_per_socket=2, power_on=true, guest_os = vcenter::LinuxGuestOS( hostname="localhost", domain="domain.local" ), children = [ vcenter::VirtualMachinePort( name="eth0", ip_address="192.168.1.2", network_mask="255.255.255.0", gateway="192.168.1.1", distributed_virtual_portgroup_path="/mydc/network/test_network", ) ] ) ``` -------------------------------- ### V2 Module Structure Example Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/language.html Provides a concrete example of a V2 module directory structure with model files. ```text test/ +-- files/ +-- model/ | +-- _init.cf | +-- services.cf | +-- policy | | +-- _init.cf | | +-- other.cf +-- inmanta_plugins/ | +-- test/ | +-- __init__.py +-- templates/ +-- pyproject.toml +-- setup.cfg ``` -------------------------------- ### Install for Configuration (Async) Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/env.html Asynchronously performs a pip install within the environment using a specified configuration. Supports requirements, paths, upgrades, and constraint files. Limitations apply to constraint file verification when not upgrading. ```python async def async_install_for_config( self, requirements: list[packaging.requirements.Requirement], config: PipConfig, upgrade: bool = False, constraint_files: Optional[list[str]] = None, upgrade_strategy: PipUpgradeStrategy = PipUpgradeStrategy.ONLY_IF_NEEDED, paths: list[LocalPackagePath] = [], ) -> None: """ Perform a pip install in this environment, according to the given config :param requirements: which requirements to install :param config: the pip config to use :param upgrade: make pip do an upgrade :param constraint_files: pass along the following constraint files :param upgrade_strategy: what upgrade strategy to use :param paths: which paths to install limitation: - When upgrade is false, if requirements are already installed constraints from constraint files may not be verified. """ if len(requirements) == 0 and len(paths) == 0: ``` -------------------------------- ### Install Project Modules Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/module.html Installs all project modules and their Python dependencies. It handles virtual environment setup and uses an eager upgrade strategy for dependencies. Optionally bypasses the module cache or updates modules to their latest versions. ```python if not self.is_using_virtual_env(): self.use_virtual_env() # install all dependencies dependencies: Sequence[inmanta.util.CanonicalRequirement] constraints: Sequence[inmanta.util.CanonicalRequirement] dependencies, constraints = self.get_all_dependencies_and_constraints() if len(dependencies) > 0: modules_pre = self.module_source.take_v2_modules_snapshot(header="Module versions before installation:") # upgrade both direct and transitive module dependencies: eager upgrade strategy self.virtualenv.install_for_config( dependencies, config=self.metadata.pip, upgrade=update, upgrade_strategy=env.PipUpgradeStrategy.EAGER, constraints=constraints, ) self.module_source.log_snapshot_difference_v2_modules( modules_pre, header="Successfully installed modules for project" ) self.load_module_recursive(bypass_module_cache=bypass_module_cache) ``` -------------------------------- ### Initialize and use Python client Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/reference/python_client.html Instantiate the client and make a call to the environment list endpoint. Asserts the result code and iterates over the returned data. ```python client = inmanta.protocol.endpoints.Client(name="api", timeout=120) result = await client.environment_list(details=True) assert result.code == 200 for key, value in result.result["data"].items(): ... ``` -------------------------------- ### Get Root Variable of Reference Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/ast/variables.html Returns the root reference node for a given reference. For example, for 'a.b.c.d', it returns the reference for 'a'. ```python def get_root_variable(self) -> "Reference": """ Returns the root reference node. e.g. for a.b.c.d, returns the reference for a. """ return self ``` -------------------------------- ### Log Post-Install Information (v1) Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/module.html Displays information after a v1 module installation, including its name, version, path, and remote repository if available. ```python def log_post_install_information(self, module: TModule) -> None: """ Display information about this module's installation after the actual installation. :param module: The module. """ local_repo = module.path remote_repo = gitprovider.get_remote(local_repo) remote_repo = f" from {remote_repo.strip()}" if remote_repo is not None else "" LOGGER.debug( "Successfully installed module %s (v1) version %s in %s%s.", module.name, module.version, module.path, remote_repo, ) ``` -------------------------------- ### Get Module Version Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/module.html Returns the currently installed version of the module as a packaging.version.Version object. This may differ from the version declared in metadata. ```python def get_version(self) -> packaging.version.Version: """ Return the version of this module. This is the actually installed version, which might differ from the version declared in its metadata (e.g. by a .dev0 tag). """ return packaging.version.Version(self._metadata.version) version = property(get_version) ``` -------------------------------- ### SR Linux CLI prompt example Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/quickstart.html Example output of a successful connection to the SR Linux CLI, showing the current mode and prompt. ```text Welcome to the srlinux CLI. Type 'help' (and press ) if you need any help using this. --{ running }--[ ]-- A:spine# ``` -------------------------------- ### Get Reports Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/reference/python_client.html Retrieves compile reports for a given environment, optionally filtered by a start and end time, and limited by a maximum number of results. ```APIDOC ## inmanta.protocol.methods.get_reports ### Description Return compile reports newer then start The returned compile report objects may carry links to other objects, e.g. a service instance. The full list of supported links can be found here. ### Parameters * **tid** (UUID) - The id of the environment to get a report from * **start** (str | None, optional) - Optional. Reports after start * **end** (str | None, optional) - Optional. Reports before end * **limit** (int | None, optional) - Optional. Maximum number of results, up to a maximum of 1000 If None, a default limit (set to 1000) is applied. ``` -------------------------------- ### Install for Configuration (Sync) Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/env.html Performs a pip install within the environment using a specified configuration. Supports requirements, paths, upgrades, and constraint files. Limitations apply to constraint file verification when not upgrading. ```python def install_for_config( self, requirements: Sequence[inmanta.util.CanonicalRequirement], config: PipConfig, upgrade: bool = False, constraint_files: Optional[list[str]] = None, upgrade_strategy: PipUpgradeStrategy = PipUpgradeStrategy.ONLY_IF_NEEDED, paths: list[LocalPackagePath] = [], add_inmanta_requires: bool = True, constraints: Sequence[inmanta.util.CanonicalRequirement] | None = None, ) -> None: """ Perform a pip install in this environment, according to the given config :param requirements: which requirements to install :param paths: which paths to install :param config: the pip config to use :param constraint_files: pass along the following constraint files :param upgrade: make pip do an upgrade :param upgrade_strategy: what upgrade strategy to use limitation: - When upgrade is false, if requirements are already installed constraints from constraint files may not be verified. """ if len(requirements) == 0 and len(paths) == 0: raise Exception("install_for_config requires at least one requirement or path to install") constraint_files = constraint_files if constraint_files is not None else [] if add_inmanta_requires: inmanta_requirements = self._get_requirements_on_inmanta_package() else: inmanta_requirements = [] with tempfile.NamedTemporaryFile() as fd: if constraints: fd.write("\n".join(str(c) for c in constraints).encode()) fd.seek(0) Pip.run_pip_install_command_from_config( python_path=self.python_path, config=config, requirements=[*requirements, *inmanta_requirements], constraints_files=[*constraint_files, fd.name], upgrade=upgrade, upgrade_strategy=upgrade_strategy, paths=paths, ) ``` -------------------------------- ### Module Source - Get Module Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/module.html Retrieves an installed module instance based on its specification. The project is responsible for verifying version constraint compatibility. ```APIDOC ## get_module ### Description Returns the appropriate module instance for a given module spec. ### Parameters - **project** (Project) - The project associated with the module. - **module_spec** (list[InmantaModuleRequirement]) - The module specification including any constraints on its version. In this case, the project is responsible for verifying constraint compatibility. ``` -------------------------------- ### Create Fortigate Interface and Policy Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/reference/modules/fortigate/README.html This example demonstrates how to create a Fortigate interface and attach a firewall policy to it. It requires the `fortigate` module and its submodules. Ensure the `FORTIGATE_API_TOKEN` environment variable is set for authentication. ```inmanta import fortigate import fortigate::base import fortigate::common import fortigate::firewall_policy api = fortigate::base::Api( token_env_var="FORTIGATE_API_TOKEN", base_url="https//example.com", ) purged = false policy = fortigate::Policy( dstaddr = [Dstaddr(name="all")], dstintf = [Dstintf(name="l2t.root")], logtraffic = "all", policyid=1, name = "test_policy_on_first_itf", schedule = "always", service = [Service(name="ALL")], srcaddr = [Srcaddr(name="all")], srcintf = [Srcintf(name=vlan_itf.name)], action = "accept", nat = 'disable', purged = purged, api = api, ) if purged: policy.provides += vlan_itf else: policy.requires += vlan_itf end vlan_itf = fortigate::Interface( name = "vlan_itf", interface = "port2", vlanid = 43, role = "lan", vdom = "root", purged = purged, api = api, ) ``` -------------------------------- ### Get Product Version Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/server/extensions.html Determines the product version by checking installed Inmanta packages. Returns '0.0.0' and logs a warning if the version cannot be determined. ```python def _get_product_version(self) -> str: packages = ["inmanta-oss", "inmanta", "inmanta-core"] for package in packages: try: return importlib.metadata.version(package) except importlib.metadata.PackageNotFoundError: pass LOGGER.warning("Couldn't determine product version. Make sure inmanta is properly installed.") return "0.0.0" ``` -------------------------------- ### Get Paging Boundaries Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/data.html Calculates the start and end boundaries for pagination based on the first and last records returned. Handles ascending and descending order. ```python def get_paging_boundaries(self, first: abc.Mapping[str, object], last: abc.Mapping[str, object]) -> PagingBoundaries: """Return the page boundaries, given the first and last record returned""" if self.get_order() == PagingOrder.ASC: first, last = last, first order_column_name = self.order_by_column order_type: ColumnType = self.get_order_by_column_type() id_column, id_type = self.id_column return PagingBoundaries( start=order_type.get_value(first[order_column_name]), first_id=id_type.get_value(first[id_column]), end=order_type.get_value(last[order_column_name]), last_id=id_type.get_value(last[id_column]), ) ``` -------------------------------- ### Deploy OCI VirtualCircuit with CrossConnect Mapping Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/reference/modules/oci_fastconnect/README.html This example demonstrates deploying an OCI VirtualCircuit in an active state and attaching it to a provider physical connection using a crossconnect mapping. It requires importing the necessary oci_fastconnect modules and configuring the provider API. ```inmanta import oci_fastconnect import oci_fastconnect::base import oci_fastconnect::virtual_circuit provider_api = oci_fastconnect::base::Api( name="provider", profile_name="provider", config_file="./config.toml", ) virtual_circuit = oci_fastconnect::VirtualCircuit( api=provider_api, name="test-circuit", id="ocid_1234", provider_state="ACTIVE", cross_connect_mappings=[ oci_fastconnect::virtual_circuit::CrossConnectMapping( cross_connect_or_cross_connect_group_id="ocid1.crossconnectgroup.oc1.test.abcdefg", vlan=42, ), ], ) oci_fastconnect::VirtualCircuitStateCheck( api=provider_api, virtual_circuit_id=virtual_circuit.id ) ``` -------------------------------- ### Get Inmanta Module Requirements Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/loader.html Retrieves the Python requirements for a given Inmanta module. It distinguishes between strict requirements and those that include dependencies for agent installation. ```python @staticmethod def get_inmanta_module_requirements(module_name: str) -> set[str]: """Get the list of python requirements associated with this inmanta module""" project: module.Project = module.Project.get() mod: module.Module = project.modules[module_name] if project.metadata.agent_install_dependency_modules: _requires = mod.get_all_python_requirements_as_list() else: _requires = mod.get_strict_python_requirements_as_list() return set(_requires) ``` -------------------------------- ### ContextV2Wrapper Initialization Example Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta_plugins/lsm/allocation_v2/framework.html Demonstrates how to initialize ContextV2Wrapper with a fallback attribute and a ForEach allocator. This setup is used for allocating values within embedded entities. ```python lsm.AllocationSpecV2( "service_allocator_spec", allocation.ContextV2Wrapper( "allocated", allocation.ForEach( item="subservice", in_list="subservices", identified_by="id", apply=[ ValueAllocator( into="to_allocate", ), ], ), ), ) ``` -------------------------------- ### Manage apt package and repository Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/reference/modules/apt/README.html Example of managing the couchdb package and its repository on a remote host. Ensure the host and necessary modules are imported. ```inmanta import apt import mitogen repo = apt::Repository( host=host, name="couchdb-deb", base_url="https://apache.bintray.com/couchdb-deb", release="bionic", repo="main", trusted=false, ) apt::Package( host=host, name="couchdb", purged=false ) host = std::Host( name="server", os=std::linux, via=mitogen::Sudo( via=mitogen::Ssh( name="server", hostname="1.2.3.4", port=22, username="user", ), ), ) ``` -------------------------------- ### Collect Slices Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/server/bootloader.html Calls the setup function on all loaded extensions to register their slices in the ApplicationContext. Can optionally skip slice registration to only collect environment settings. ```python def _collect_slices( self, extensions: dict[str, ModuleType], only_register_environment_settings: bool = False, ) -> ApplicationContext: """ Call the setup function on all extensions and let them register their slices in the ApplicationContext. """ ctx = ApplicationContext() for name, ext_module in extensions.items(): myctx = ConstrainedApplicationContext(ctx, name) self._collect_environment_settings(ext_module, myctx) if not only_register_environment_settings: ext_module.setup(myctx) return ctx ``` -------------------------------- ### Configure New Orchestrator for Boot (Container) Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/administrators/upgrading_the_orchestrator.html Ensure this section is NOT present in the inmanta-server.container file to prevent the server from starting at boot during the upgrade process for container-based installations. ```ini [Install] WantedBy=default.target ``` -------------------------------- ### Example YAML Configuration File Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/reference/modules/config/README.html A sample YAML file demonstrating the structure expected by the configuration model. Values correspond to the fields defined in the Python configuration class. ```yaml a: hah b: - c: 1 d: true e: aha c: inmanta:///templates/test.j2 ``` -------------------------------- ### Get All Configuration Models for Environment Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/data.html Fetches all configuration models for a given environment, ordered by version in descending order. Supports pagination with start and limit parameters. ```python @classmethod async def get_versions( cls, environment: uuid.UUID, start: int = 0, limit: int = DBLIMIT, connection: Optional[Connection] = None, ) -> list["ConfigurationModel"]: """ Get all versions for an environment ordered descending """ versions = await cls.get_list( order_by_column="version", order="DESC", limit=limit, offset=start, environment=environment, connection=connection ) return versions ``` -------------------------------- ### Basic main.cf Entry Point Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/model_developers/project_creation.html The main configuration file where Inmanta execution begins. This example calls the print plugin from the std module. ```inmanta 1std::print("hello world") ``` -------------------------------- ### Get Plain Attributes Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta_plugins/lsm.html Retrieves a set of attribute names that are neither relational nor metadata attributes. It excludes attributes starting with underscores or containing double underscores. ```python attributes, _ = cls._get_all_attributes_compiler_type(entity) return set( name for name, attr in attributes.items() if not ( name.startswith("_") or "__" in name or isinstance(attr, ast.attribute.RelationAttribute) ) ) ``` -------------------------------- ### List Versions Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/reference/commands.html Lists all deployed versions of the configuration model in a specified environment. Requires the environment name. ```bash inmanta-cli version list [OPTIONS] ``` -------------------------------- ### async_install_for_config Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/env.html Asynchronously performs a pip install in the environment using the provided configuration, requirements, and optional constraints. ```APIDOC ## async_install_for_config ### Description Perform a pip install in this environment, according to the given config. ### Method Signature `async_install_for_config(self, requirements: list[packaging.requirements.Requirement], config: PipConfig, upgrade: bool = False, constraint_files: Optional[list[str]] = None, upgrade_strategy: PipUpgradeStrategy = PipUpgradeStrategy.ONLY_IF_NEEDED, paths: list[LocalPackagePath] = []) -> None` ### Parameters - **requirements** (list[packaging.requirements.Requirement]) - Which requirements to install. - **config** (PipConfig) - The pip config to use. - **upgrade** (bool) - Make pip do an upgrade. Defaults to False. - **constraint_files** (Optional[list[str]]) - Pass along the following constraint files. - **upgrade_strategy** (PipUpgradeStrategy) - What upgrade strategy to use. Defaults to PipUpgradeStrategy.ONLY_IF_NEEDED. - **paths** (list[LocalPackagePath]) - Which paths to install. ### Limitation - When upgrade is false, if requirements are already installed constraints from constraint files may not be verified. ``` -------------------------------- ### Get Inmanta Module Version Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/module.html Retrieves the version of an installed Inmanta module. Raises ValueError for Python package names and returns None if the module is not found. ```python def get_installed_version(self, module_name: str) -> Optional[packaging.version.Version]: """ Returns the version for a module if it is installed. """ if module_name.startswith(ModuleV2.PKG_NAME_PREFIX): raise ValueError("PythonRepo instances work with inmanta module names, not Python package names.") try: return packaging.version.Version(importlib.metadata.version(ModuleV2Source.get_package_name_for(module_name))) except PackageNotFoundError: return None ``` -------------------------------- ### Get Python Package Requirement for Inmanta Module Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/module.html Converts an Inmanta module requirement into a Python package requirement. This is useful for installing modules via pip. ```python def get_python_package_requirement(self) -> inmanta.util.CanonicalRequirement: """ Return a Requirement with the name of the Python distribution package for this module requirement. """ module_name = self.name pkg_name = ModuleV2Source.get_package_name_for(module_name) pkg_req_str = str(self).replace(module_name, pkg_name, 1) # Replace max 1 occurrence return inmanta.util.parse_requirement(requirement=pkg_req_str) ``` -------------------------------- ### Get Total Length of All Compile Queues Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/_modules/inmanta/data.html Returns the total number of compiles across all queues on the Inmanta server. Optionally excludes compiles that have started but not yet finished. ```APIDOC ## get_total_length_of_all_compile_queues(exclude_started_compiles: bool = True) -> int ### Description Return the total length of all the compile queues on the Inmanta server. ### Parameters #### Query Parameters - **exclude_started_compiles** (bool) - Optional - True iff don't count compiles that started running, but are not finished yet. Defaults to True. ### Returns - int - The total number of compiles in the queues. ``` -------------------------------- ### Document Netbox Resources Source: https://docs.inmanta.com/inmanta-service-orchestrator/9/reference/modules/netbox/README.html This example demonstrates how to document various Netbox resources including tenants, sites, racks, device types, and devices. It requires the netbox and restbase modules. ```inmanta import netbox import netbox::resources import restbase credentials = netbox::Credentials( url="http://1.2.3.4:8000", api_token="abcdefg", agent_autostart=false ) tenant_group=netbox::resources::TenantGroup( credentials=credentials, name="tenant_group_1", slug="tenant_group_1", purged=false, ) tenant=netbox::resources::Tenant( credentials=credentials, name="tenant1", slug="tenant1", group=tenant_group, purged=false, ) site = netbox::resources::Site( credentials=credentials, name="SITE", slug="site", tenant=tenant, purged=false, ) rack1 = netbox::resources::Rack( credentials=credentials, name="rack-1", site=site, tenant=tenant, purged=false, ) lenovo = netbox::resources::Manufacturer( credentials=credentials, name="Lenovo", slug="lenovo", purged=false ) se450 = netbox::resources::DeviceType( credentials=credentials, model="SE450", slug="se450", manufacturer=lenovo, purged=false, ) server_role = netbox::resources::DeviceRole( credentials=credentials, name="server", slug="server", purged=false, ) cluster_type = netbox::resources::ClusterType( credentials=credentials, name="esxi", slug="esxi", purged=false ) cluster1 = netbox::resources::Cluster( credentials=credentials, type=cluster_type, name="server-1", site=site, tenant=tenant, purged=false, ) device_server = netbox::resources::Device( credentials=credentials, name="server-1", site=site, rack=rack1, tenant=tenant, device_type = se450, role = server_role, cluster=cluster1, purged=false ) ```