### Define Resource Sets for Basic Example Source: https://github.com/inmanta/inmanta-core/blob/master/docs/model_developers/resource_sets.rst This example demonstrates how to define resource sets, where each host is part of its network's resource set. This setup is used to illustrate partial compilation. ```inmanta import network std::ResourceSet("network_0", [network::Network("net0"), network::Host("host0_0", network="net0"), network::Host("host0_1", network="net0"), network::Host("host0_2", network="net0"), network::Host("host0_3", network="net0"), network::Host("host0_4", network="net0")]), std::ResourceSet("network_1", [network::Network("net1"), network::Host("host1_0", network="net1"), network::Host("host1_1", network="net1"), network::Host("host1_2", network="net1"), network::Host("host1_3", network="net1"), network::Host("host1_4", network="net1")]), std::ResourceSet("network_2", [network::Network("net2"), network::Host("host2_0", network="net2"), network::Host("host2_1", network="net2"), network::Host("host2_2", network="net2"), network::Host("host2_3", network="net2"), network::Host("host2_4", network="net2")]), std::ResourceSet("network_3", [network::Network("net3"), network::Host("host3_0", network="net3"), network::Host("host3_1", network="net3"), network::Host("host3_2", network="net3"), network::Host("host3_3", network="net3"), network::Host("host3_4", network="net3")]), std::ResourceSet("network_4", [network::Network("net4"), network::Host("host4_0", network="net4"), network::Host("host4_1", network="net4"), network::Host("host4_2", network="net4"), network::Host("host4_3", network="net4"), network::Host("host4_4", network="net4")]), std::ResourceSet("network_5", [network::Network("net5"), network::Host("host5_0", network="net5"), network::Host("host5_1", network="net5"), network::Host("host5_2", network="net5"), network::Host("host5_3", network="net5"), network::Host("host5_4", network="net5")]), std::ResourceSet("network_6", [network::Network("net6"), network::Host("host6_0", network="net6"), network::Host("host6_1", network="net6"), network::Host("host6_2", network="net6"), network::Host("host6_3", network="net6"), network::Host("host6_4", network="net6")]), std::ResourceSet("network_7", [network::Network("net7"), network::Host("host7_0", network="net7"), network::Host("host7_1", network="net7"), network::Host("host7_2", network="net7"), network::Host("host7_3", network="net7"), network::Host("host7_4", network="net7")]), std::ResourceSet("network_8", [network::Network("net8"), network::Host("host8_0", network="net8"), network::Host("host8_1", network="net8"), network::Host("host8_2", network="net8"), network::Host("host8_3", network="net8"), network::Host("host8_4", network="net8")]), std::ResourceSet("network_9", [network::Network("net9"), network::Host("host9_0", network="net9"), network::Host("host9_1", network="net9"), network::Host("host9_2", network="net9"), network::Host("host9_3", network="net9"), network::Host("host9_4", network="net9")]), ``` -------------------------------- ### Module Metadata Configuration (setup.cfg) Source: https://github.com/inmanta/inmanta-core/blob/master/docs/reference/projectyml.rst Example of a complete setup.cfg file for a V2 module, defining metadata such as name, description, version, license, and compiler version, along with installation requirements. ```ini [metadata] name = inmanta-module-openstack description = A module to manage networks, routers, virtual machine, etc. on an Openstack cluster. version = 3.7.1 license = Apache 2.0 compiler_version = 2020.2 freeze_recursive = false freeze_operator = ~= [options] install_requires = inmanta-modules-ip ``` -------------------------------- ### Initial User Setup JWT Configuration Output Source: https://github.com/inmanta/inmanta-core/blob/master/docs/administrators/authentication.rst Example output from `inmanta-initial-user-setup` command, showing a generated JWT configuration. This configuration should be added to `/etc/inmanta/inmanta.d/auth.cfg`. ```ini [auth_jwt_default] algorithm=HS256 sign=true client_types=agent,compiler,api key=NYR2LtAsKSs7TuY0D8ZIqmMaLcICC3lf_ur4FGlLUcQ expire=0 issuer=https://localhost:8888/ audience=https://localhost:8888/ ``` -------------------------------- ### Start and Enable PostgreSQL Service Source: https://github.com/inmanta/inmanta-core/blob/master/docs/install/2-install-postgresql-orchestrator.rst Starts the PostgreSQL database and ensures it is enabled to start automatically at boot. ```sh sudo systemctl enable --now postgresql ``` -------------------------------- ### Example Inmanta Model for Partial Compiles Source: https://github.com/inmanta/inmanta-core/blob/master/docs/lsm/partial_compiles/partial_compiles.rst This example demonstrates an Inmanta model for managing ports and routers, illustrating how to set up inter-service relations for partial compilation. Lines 29, 38, and 58-59 are highlighted as key for this setup. ```inmanta import lsm import std::system # Define a service entity for a router @lsm::ServiceEntity entity Router extends lsm::ServiceBase { # Define a relation to owned resources, including ports relation owned_resources = ports # Define a relation for ports associated with this router relation ports = Port[self] } # Define a service entity for a port @lsm::ServiceEntity entity Port extends lsm::ServiceBase { # Define a relation to owned resources, which includes the router it belongs to relation owned_resources = [router] # Define the router this port belongs to relation router } # Define a service entity for a null resource, used as a placeholder or base @lsm::ServiceEntity entity NullResource extends lsm::ServiceBase { # Define a relation to owned resources, which is empty for NullResource relation owned_resources = [] } # Define a service entity for lifecycle transfer, used for managing service lifecycles @lsm::ServiceEntity entity LifecycleTransfer extends lsm::ServiceBase { # Define a relation to owned resources, which includes the null resource it transfers lifecycle to relation owned_resources = [null_resource] # Define the null resource for lifecycle transfer relation null_resource } # Instantiate a router named 'r1' service r1 = Router() # Instantiate a port named 'p1' associated with router 'r1' service p1 = Port(router=r1) # Instantiate a lifecycle transfer service, linking to the null resource 'r1' service lt = LifecycleTransfer(null_resource=r1) # Instantiate another router named 'r2' service r2 = Router() # Instantiate a port named 'p2' associated with router 'r2' service p2 = Port(router=r2) # Instantiate another lifecycle transfer service, linking to the null resource 'r2' service lt2 = LifecycleTransfer(null_resource=r2) ``` -------------------------------- ### Navigate to SR Linux Examples Directory Source: https://github.com/inmanta/inmanta-core/blob/master/docs/quickstart.rst Change the current directory to the SR Linux examples folder. This is where the project configuration files are located. ```sh cd examples/Networking/SR\ Linux/ ``` -------------------------------- ### Set up Python Virtual Environment and Install Inmanta Source: https://github.com/inmanta/inmanta-core/blob/master/docs/quickstart.rst Create a Python virtual environment and install the Inmanta package. This is a prerequisite for using Inmanta. ```sh mkdir -p ~/.virtualenvs python3 -m venv ~/.virtualenvs/srlinux source ~/.virtualenvs/srlinux/bin/activate pip install inmanta ``` -------------------------------- ### Navigate to LSM SR Linux Example Directory Source: https://github.com/inmanta/inmanta-core/blob/master/docs/lsm/quickstart/quickstart.rst Changes the current directory to the location of the LSM SR Linux example within the Inmanta examples repository. This is necessary to access project configuration files. ```bash $ cd examples/lsm-srlinux ``` -------------------------------- ### Start and Enable PostgreSQL Service on Standby Source: https://github.com/inmanta/inmanta-core/blob/master/docs/administrators/ha-setup.rst Start the PostgreSQL service on the standby node and enable it to start automatically on boot. Ensure the synchronous_standby_names setting is commented out in postgresql.conf on the standby. ```sh $ sudo systemctl start postgresql $ sudo systemctl enable postgresql ``` -------------------------------- ### Complete project.yml Example Source: https://github.com/inmanta/inmanta-core/blob/master/docs/reference/projectyml.rst A comprehensive example of a project.yml file, demonstrating various configuration options for project metadata, module paths, repositories, dependencies, and pip settings. ```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 ``` -------------------------------- ### DictPath Usage Examples Source: https://github.com/inmanta/inmanta-core/blob/master/docs/model_developers/dictpath.rst Demonstrates how to use the DictPath library to get and set elements within nested data structures. ```APIDOC ## DictPath Usage Examples This section provides examples of how to use the `dict_path` library in Python. ### Functions - `dict_path.to_path(expression)`: Converts a dictpath expression string into a `DictPath` instance. - `dict_path.to_wild_path(expression)`: Converts a dictpath expression string into a `DictPath` instance, allowing wildcards. ### Class: DictPath - `DictPath.get_element(collection)`: Retrieves a single element from a collection using the DictPath. - `DictPath.get_elements(collection)`: Retrieves all matching elements from a collection using the DictPath (typically with wildcards). - `DictPath.set_element(collection, value)`: Sets a value for a specific element within a collection using the DictPath. ### Example Code ```python from inmanta.util import dict_path container = { "a": "b", "c": { "e": "f" }, "g": [ {"h": "i", "j": "k"}, {"h": "a", "j": "b"} ] } # Get elements assert dict_path.to_path("a").get_element(container) == "b" assert dict_path.to_path("c.e").get_element(container) == "f" assert dict_path.to_path("g[h=i]").get_element(container) == {"h": "i", "j": "k"} # Using wildcards assert dict_path.to_wild_path("c.*").get_elements(container) == ["f"] assert sorted(dict_path.to_wild_path("g[h=i].*").get_elements(container)) == ["i", "k"] assert dict_path.to_wild_path("g[*=k]").get_elements(container) == [{"h": "i", "j": "k"}] # Set elements dict_path.to_path("g[h=b].i").set_element(container, "z") assert dict_path.to_path("g[h=b]").get_element(container) == {"h": "b", "i": "z"} assert dict_path.to_path("g[h=b].i").get_element(container) == "z" ``` ``` -------------------------------- ### Install English Language Pack (RHEL 9) Source: https://github.com/inmanta/inmanta-core/blob/master/docs/install/2-install-postgresql-orchestrator.rst Installs the 'en_US.UTF-8' locale, which is the default for RHEL 9 and required before proceeding with PostgreSQL setup. ```sh sudo dnf install langpacks-en -y ``` -------------------------------- ### Install Project Module Dependencies Source: https://github.com/inmanta/inmanta-core/blob/master/docs/model_developers/developer_getting_started.rst After creating or cloning a project, use the inmanta CLI to install its module dependencies. This command reads the project configuration and installs necessary modules. ```bash inmanta project install ``` -------------------------------- ### Install PostgreSQL Server (RHEL) Source: https://github.com/inmanta/inmanta-core/blob/master/docs/install/2-install-postgresql-orchestrator.rst Installs the PostgreSQL server package using DNF module streams. This command is applicable for both OSS and ISO installations on RHEL-based systems. ```sh sudo dnf module install postgresql:|pg_version|/server ``` -------------------------------- ### Registering Server Slices and Settings Source: https://github.com/inmanta/inmanta-core/blob/master/docs/platform_developers/create_server_extension.rst 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." ) ) ``` -------------------------------- ### Install Test Dependencies Source: https://github.com/inmanta/inmanta-core/blob/master/docs/model_developers/developer_getting_started.rst Install the required dependencies for testing using pip. ```bash pip install -r requirements.txt -r requirements.dev.txt ``` -------------------------------- ### Install Podman Source: https://github.com/inmanta/inmanta-core/blob/master/docs/install/1-install-server-with-podman-and-systemd.rst Installs Podman on RedHat Enterprise Linux and derivatives using dnf. ```console $ sudo dnf -y install podman ``` -------------------------------- ### Execute Setup Script in Docker Container Source: https://github.com/inmanta/inmanta-core/blob/master/docs/lsm/quickstart/quickstart.rst Command to execute a setup script inside a Docker container, likely for environment initialization. ```bash $ docker exec -ti -w /code clab-srlinux-inmanta-server /code/setup.sh ``` -------------------------------- ### Create Python Virtual Environment and Install Inmanta Source: https://github.com/inmanta/inmanta-core/blob/master/docs/lsm/quickstart/quickstart.rst Sets up a dedicated Python virtual environment and installs the Inmanta package. This is a standard practice for managing project dependencies. ```bash $ mkdir -p ~/.virtualenvs $ python3 -m venv ~/.virtualenvs/lsm-srlinux $ source ~/.virtualenvs/lsm-srlinux/bin/activate $ pip install inmanta ``` -------------------------------- ### Install Inmanta from Current Checkout Source: https://github.com/inmanta/inmanta-core/blob/master/docs/platform_developers/platform.rst Installs the Inmanta platform from the current source checkout using pinned dependencies from requirements.txt. ```sh # Install inmanta from current checkout pip install -c requirements.txt . ``` -------------------------------- ### External Postgres Allocation Example Source: https://github.com/inmanta/inmanta-core/blob/master/docs/lsm/allocation/allocation.rst This example demonstrates how to allocate resources using an external PostgreSQL database. It shows how to check for existing allocations before attempting a new one, which is crucial for recovering from failed operations. ```python import logging from inmanta.plugins import Plugin, Resource from inmanta.types import Id LOGGER = logging.getLogger(__name__) class PGAllocation(Resource): def __init__(self, name, service_instance, **kwargs): Resource.__init__(self, name, service_instance, **kwargs) def get_id(self): return Id(self.name) def get_allocation_id(self): return self.get_id() def get_allocation_key(self): return self.get_id() class PGAllocationPlugin(Plugin): def allocate(self, resource): LOGGER.info("Allocating resource %s", resource.get_allocation_key()) # Check if already allocated if self.lookup(resource.get_allocation_key()): LOGGER.info("Resource %s already allocated", resource.get_allocation_key()) return # Allocate self.insert(resource.get_allocation_key(), resource.get_allocation_id()) LOGGER.info("Resource %s allocated with id %s", resource.get_allocation_key(), resource.get_allocation_id()) def lookup(self, key): # In a real implementation, this would query the database # For this example, we assume it's always allocated return True def insert(self, key, id): # In a real implementation, this would insert into the database pass def delete(self, key): # In a real implementation, this would delete from the database pass ``` -------------------------------- ### Start Inmanta Server Service Source: https://github.com/inmanta/inmanta-core/blob/master/docs/install/1-install-server-with-podman-and-systemd.rst Starts the Inmanta server and its database dependency. This command may take time as it downloads container images. ```console systemctl --user start inmanta-server.service ``` -------------------------------- ### Install Development Dependencies for Existing Project Source: https://github.com/inmanta/inmanta-core/blob/master/docs/model_developers/developer_getting_started.rst Install development dependencies for an existing project using its `requirements.dev.txt` file. This ensures all necessary tools for development are available. ```bash pip install -r requirements.dev.txt ``` -------------------------------- ### Clone SR Linux Examples Repository Source: https://github.com/inmanta/inmanta-core/blob/master/docs/quickstart.rst Clone the repository containing SR Linux examples for Inmanta. This repository includes necessary project files. ```sh git clone https://github.com/inmanta/examples.git ``` -------------------------------- ### Enable PostgreSQL Service (RHEL 9) Source: https://github.com/inmanta/inmanta-core/blob/master/docs/install/2-install-postgresql-orchestrator.rst Enables the PostgreSQL service to start on boot for RHEL 9 systems. ```sh sudo systemctl enable postgresql ``` -------------------------------- ### Example with Duplication (Before Embedded Entities) Source: https://github.com/inmanta/inmanta-core/blob/master/docs/lsm/embedded_entities/embedded_entities.rst This example demonstrates code duplication before utilizing embedded entities. ```inmanta entity ServiceEntity: # ... attributes ... router_name: string router_ip: string router_port: integer entity OtherServiceEntity: # ... attributes ... router_name: string router_ip: string router_port: integer ``` -------------------------------- ### Install Core Inmanta Packages Source: https://github.com/inmanta/inmanta-core/blob/master/docs/model_developers/developer_getting_started.rst Install the essential inmanta-core and pytest-inmanta packages for new projects. These provide the core Inmanta functionality and testing utilities. ```bash pip install inmanta-core pytest-inmanta ``` -------------------------------- ### Install Inmanta CLI Source: https://context7.com/inmanta/inmanta-core/llms.txt Basic command to install the Inmanta CLI tool using pip. This is a prerequisite for using the `inmanta compile` command. ```bash # Install Inmanta pip install inmanta ``` -------------------------------- ### Install Module in Editable Mode Source: https://github.com/inmanta/inmanta-core/blob/master/docs/model_developers/modules.rst Check out a module's repository separately and run this command to install it in editable mode. This allows any changes made to the checked-out files to be picked up by the compiler. ```bash pip install -e ``` -------------------------------- ### Example of Mypy Type Checking Source: https://github.com/inmanta/inmanta-core/blob/master/docs/reference/python_client.rst A Python code example demonstrating the usage of the Inmanta client that can be checked by the mypy plugin. ```python client = inmanta.protocol.endpoints.Client(name="api", timeout=120) env_id: str = "123" result = await client.resource_list(env_id) ``` -------------------------------- ### Partial Compile Example Source: https://github.com/inmanta/inmanta-core/blob/master/docs/model_developers/resource_sets.rst This example shows a model that is partially compiled, including only the entities and resources for the resource sets that need to be changed. This facilitates quicker compilations by only recompiling a small portion of the model. ```inmanta import network std::ResourceSet("network_0", [network::Network("net0"), network::Host("host0_0", network="net0")]), ``` -------------------------------- ### Basic Example Using Embedded Entity (Router) Source: https://github.com/inmanta/inmanta-core/blob/master/docs/lsm/embedded_entities/embedded_entities.rst This example shows how to refactor code using an embedded entity named Router to avoid duplication. ```inmanta entity Router: name: string ip: string port: integer index name entity ServiceEntity: # ... attributes ... router: Router entity OtherServiceEntity: # ... attributes ... router: Router ``` -------------------------------- ### JWT Auth Configuration Example Source: https://github.com/inmanta/inmanta-core/blob/master/docs/administrators/authentication.rst Example INI configuration for JWT authentication. Ensure 'sign' is true for only one section. The 'key' should be a urlsafe base64 encoded bytestring. ```ini [auth_jwt_default] algorithm=HS256 sign=true client_types=agent,compiler,api key=rID3kG4OwGpajIsxnGDhat4UFcMkyFZQc1y3oKQTPRs expire=0 issuer=https://localhost:8888/ audience=https://localhost:8888/ ``` -------------------------------- ### V2 Plugin Allocation Baseline Source: https://github.com/inmanta/inmanta-core/blob/master/docs/lsm/allocation/allocation_v3.rst Example of baseline V2 allocation logic within a plugin's `__init__.py` file. ```python from inmanta.plugins import plugin from inmanta.resources import Resource from inmanta.util import dict_path @plugin def needs_allocation(service: Resource, attribute_path: dict_path.DictPath) -> bool: return True @plugin def allocate(service: Resource, attribute_path: dict_path.DictPath) -> None: if attribute_path == dict_path.DictPath("service_id"): service["service_id"] = 1 elif attribute_path == dict_path.DictPath("port"): service["port"] = 8080 ``` -------------------------------- ### Create a Python Virtual Environment Source: https://github.com/inmanta/inmanta-core/blob/master/docs/model_developers/developer_getting_started.rst Use this command to create a new virtual environment for your project. Ensure you have Python 3 installed. ```bash python3 -m venv ~/.virtualenvs/my_project ``` -------------------------------- ### Define Entities in Configuration Model Source: https://github.com/inmanta/inmanta-core/blob/master/docs/language.rst Example of defining an 'File' entity with various attribute types and default values. ```inmanta entity File: string path string content int mode = 640 string[] list = [] dict things = {} end ``` -------------------------------- ### Project YAML Configuration Source: https://github.com/inmanta/inmanta-core/blob/master/docs/quickstart.rst This is an example of a project.yml file used by Inmanta. It defines project metadata, module paths, and pip index URLs. ```yaml name: SR Linux Examples description: Provides examples for the SR Linux module author: Inmanta author_email: code@inmanta.com license: ASL 2.0 copyright: 2022 Inmanta modulepath: libs downloadpath: libs pip: index_url: https://packages.inmanta.com/public/quickstart/python/simple/ ``` -------------------------------- ### Disable and Stop Inmanta Server (RPM) Source: https://github.com/inmanta/inmanta-core/blob/master/docs/administrators/upgrading_the_orchestrator.rst For RPM-based installations, disable the inmanta-server service to prevent it from starting automatically and then stop it. ```bash sudo systemctl disable --now inmanta-server.service ``` -------------------------------- ### Basic Client Initialization and Environment Listing Source: https://github.com/inmanta/inmanta-core/blob/master/docs/reference/python_client.rst Demonstrates how to initialize the Inmanta client and list environments with details. ```APIDOC ## Client Initialization and Environment Listing ### Description Initialize the Inmanta client and retrieve a list of environments, including detailed information. ### Method ```python client = inmanta.protocol.endpoints.Client(name="api", timeout=120) result = await client.environment_list(details=True) ``` ### Parameters * `name` (str): The name of the client. * `timeout` (int): The timeout for API requests in seconds. * `details` (bool): If True, return detailed information about the environments. ``` -------------------------------- ### Configure Inmanta Server Systemd Service Source: https://github.com/inmanta/inmanta-core/blob/master/docs/administrators/logging.rst Example of how to configure the systemd service file for the Inmanta server to enable specific logging options. ```text [Unit] Description=The server of the Inmanta platform After=network.target [Service] Type=simple User=inmanta Group=inmanta ExecStart=/usr/bin/inmanta --log-file /var/log/inmanta/server.log --log-file-level INFO --timed-logs server Restart=on-failure [Install] WantedBy=multi-user.target ``` -------------------------------- ### Example setup.cfg for Inmanta Module Metadata Source: https://github.com/inmanta/inmanta-core/blob/master/docs/model_developers/modules.rst Defines metadata, dependencies, and packaging options for an Inmanta module. Ensure dependencies are managed with 'inmanta module add'. ```ini [metadata] name = inmanta-module-mod1 version = 1.2.3 license = Apache 2.0 [options] install_requires = inmanta-modules-net ~=0.2.4 inmanta-modules-std >1.0,<2.5 cookiecutter~=1.7.0 cryptography>1.0,<3.5 [options.extras_require] feature-x = inmanta-modules-mod2 zip_safe=False include_package_data=True packages=find_namespace: [options.packages.find] include = inmanta_plugins* ``` -------------------------------- ### Configure Production Pip Index Source: https://github.com/inmanta/inmanta-core/blob/master/docs/reference/projectyml.rst Example configuration for a production environment's pip settings. It sets a secure internal repository as the primary index and disables pre-release versions for stable module installations. ```yaml pip: index-url: ``` -------------------------------- ### Configure Development Pip Index Source: https://github.com/inmanta/inmanta-core/blob/master/docs/reference/projectyml.rst Example configuration for a development environment's pip settings. It specifies a custom index URL, disables extra indexes, and enables pre-release versions for module installations. ```yaml pip: index-url: https://my_repo.secure.example.com/repository/dev extra-index-url: [] pre: true use-system-config: false ``` -------------------------------- ### Load and Dump Configuration Source: https://context7.com/inmanta/inmanta-core/llms.txt Demonstrates how to load configuration from a dictionary and retrieve the active configuration. Useful for testing or in-process configuration manipulation. ```python from inmanta.config import Config # Load from a dict (for testing / in-process config copying) Config.load_config_from_dict({ "config": {"state_dir": "/tmp/inmanta-state", "environment": "abc123"}, "server": {"port": "8888"}, }) # Dump currently active configuration active = Config.get_active_configuration_as_dict() print(active["server"]["port"]) # => 8888 ``` -------------------------------- ### Importing Modules and Aliases Source: https://github.com/inmanta/inmanta-core/blob/master/docs/cheatsheet.rst Shows how to import modules and sub-namespaces, and how to use aliases for brevity. ```inmanta import mymodule import mymodule::subns import mymodule::subns as sub ``` -------------------------------- ### Create Minimal Inmanta Project Source: https://context7.com/inmanta/inmanta-core/llms.txt Sets up a basic Inmanta project structure with a `project.yml` configuration and a simple `main.cf` model file. ```bash mkdir myproject && cd myproject cat > project.yml <<'EOF' name: myproject modulepath: libs downloadpath: libs pip: index_url: https://packages.inmanta.com/public/quickstart/python/simple/ EOF cat > main.cf <<'EOF' import std host = std::Host(name="web01", os=std::linux) file = std::File( host=host, path="/etc/motd", content="Managed by Inmanta\n", owner="root", group="root", mode="644" ) EOF ``` -------------------------------- ### Instantiate Entities and Assign Relations Source: https://github.com/inmanta/inmanta-core/blob/master/docs/language.rst Demonstrates creating multiple 'File' instances and assigning them to a 'Host' entity's relation. Also shows how to assign multiple values to a relation and that adding duplicates has no effect. ```inmanta Host.files [0:] -- File.host [1] h1 = Host("test") f1 = File(host=h1, path="/opt/1") f2 = File(host=h1, path="/opt/2") f3 = File(host=h1, path="/opt/3") # h1.files equals [f1, f2, f3] FileSet.files [0:] -- File.set [1] s1 = FileSet() s1.files = [f1,f2] s1.files = f3 # s1.files equals [f1, f2, f3] s1.files = f3 # adding a value twice does not affect the relation, # s1.files still equals [f1, f2, f3] ``` -------------------------------- ### Start Inmanta Server Service Source: https://github.com/inmanta/inmanta-core/blob/master/docs/administrators/ha-setup.rst Starts the Inmanta server service after reconfiguration or failover. ```sh $ sudo systemctl start inmanta-server ``` -------------------------------- ### Basic inmanta configuration file (main.cf) Source: https://github.com/inmanta/inmanta-core/blob/master/docs/model_developers/project_creation.rst The main entry point for Inmanta compiler execution. This example demonstrates calling the print plugin from the std module. ```inmanta std::print("hello world") ``` -------------------------------- ### Prepare Directories for Bind Mounts Source: https://github.com/inmanta/inmanta-core/blob/master/docs/install/1-install-server-with-podman-and-systemd.rst Creates necessary directories for the Inmanta orchestrator and its PostgreSQL database to use as bind mounts for persistent storage. ```console $ mkdir -p /home/inmanta/mount/{db,orchestrator} $ mkdir -p /home/inmanta/mount/orchestrator/{log,state,config} ``` -------------------------------- ### Install Pytest-Inmanta-tests via Makefile Source: https://github.com/inmanta/inmanta-core/blob/master/tests_common/README.md A convenience command to install the test package using the project's Makefile. ```bash make install-tests ``` -------------------------------- ### Deprecated Plugin Warning Example Source: https://github.com/inmanta/inmanta-core/blob/master/docs/model_developers/plugins.rst This is an example of a deprecation warning generated when a plugin is marked as deprecated with a specified replacement. ```text Plugin 'printf' in module 'inmanta_plugins.' is deprecated. It should be replaced by 'my_new_plugin' ``` -------------------------------- ### Navigate to Containerlab Directory Source: https://github.com/inmanta/inmanta-core/blob/master/docs/lsm/quickstart/quickstart.rst Changes the current directory to the 'containerlab' subdirectory within the example project. This is where container lab deployment configurations are typically located. ```bash $ cd containerlab ``` -------------------------------- ### Install pytest-inmanta Package Source: https://github.com/inmanta/inmanta-core/blob/master/docs/model_developers/test_plugins.rst Install the pytest-inmanta package using pip. This package provides fixtures for testing Inmanta plugins. ```sh pip install pytest-inmanta ``` -------------------------------- ### Create Initial Inmanta User Source: https://github.com/inmanta/inmanta-core/blob/master/docs/administrators/authentication.rst Use this command to set up the initial administrator user for Inmanta. Ensure the password meets the minimum length requirement. ```bash $ /opt/inmanta/bin/inmanta-initial-user-setup This command should be execute locally on the orchestrator you want to configure. Are you running this command locally? [y/N]: y Server authentication: enabled Server authentication method: database Authentication signing config: found Trying to connect to DB: inmanta (localhost:5432) Connection to database success What username do you want to use? [admin]: What password do you want to use?: User admin: created Make sure to (re)start the orchestrator to activate all changes. ``` -------------------------------- ### Show Inmanta Configuration Options Source: https://github.com/inmanta/inmanta-core/blob/master/docs/platform_developers/documentation.rst Use the `show-options` directive to document Inmanta configuration options. This directive requires the configuration module path. ```rst .. show-options:: inmanta.server.config inmanta.agent.config ``` -------------------------------- ### Initialize and Use Python Client Source: https://github.com/inmanta/inmanta-core/blob/master/docs/reference/python_client.rst Initializes the Inmanta Python client and demonstrates a basic API call to list environments. ```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(): ... ``` -------------------------------- ### MANIFEST.in for Including Module Files Source: https://github.com/inmanta/inmanta-core/blob/master/docs/model_developers/modules.rst Configures setuptools to include specific directories and files in the Inmanta module package. This example ensures model files, plugins, and data files are packaged. ```text include inmanta_plugins/mod1/setup.cfg recursive-include inmanta_plugins/mod1/model *.cf graft inmanta_plugins/mod1/files ``` -------------------------------- ### Install Pytest-Inmanta-tests Manually Source: https://github.com/inmanta/inmanta-core/blob/master/tests_common/README.md Installs necessary build tools and then the package. The `copy_files_from_core.py` script is used to copy required files from the core tests directory. ```bash pip install -U setuptools pip python3 tests_common/copy_files_from_core.py pip install tests_common/ ``` -------------------------------- ### Check Initial Interface Configuration Source: https://github.com/inmanta/inmanta-core/blob/master/docs/lsm/quickstart/quickstart.rst Verify the initial interface configuration on the SR Linux router before deploying the service. ```cli A:spine# list interface interface ethernet-1/1 { } interface ethernet-1/2 { } interface mgmt0 { subinterface 0 { ipv4 { dhcp-client { } } ipv6 { dhcp-client { } } } ``` -------------------------------- ### Reload systemd and start the Inmanta server service Source: https://github.com/inmanta/inmanta-core/blob/master/docs/administrators/upgrading_the_orchestrator.rst Reload the systemd user daemon configuration and start the inmanta-server.service. Database migrations may occur during startup. ```bash systemctl --user daemon-reload systemctl --user start inmanta-server.service ``` -------------------------------- ### Install rpdb for Server Debugging Source: https://github.com/inmanta/inmanta-core/blob/master/docs/troubleshooting.rst Install the 'rpdb' package into the Inmanta virtual environment using pip. This package is required to enable remote debugging of the Inmanta server. ```sh $ /opt/inmanta/bin/python3 -m pip install rpdb ``` -------------------------------- ### Run Inmanta Tests with Tox Source: https://github.com/inmanta/inmanta-core/blob/master/README.md This snippet shows how to set up a virtual environment, install dependencies, and run the Inmanta test suite using tox. Additional pytest arguments can be passed via the INMANTA_EXTRA_PYTEST_ARGS environment variable. ```bash $ python3 -m venv env $ source env/bin/activate $ pip install -U pip tox $ tox ``` -------------------------------- ### Create Inmanta Project and Environment Source: https://github.com/inmanta/inmanta-core/blob/master/docs/lsm/quickstart/quickstart.rst Commands to create a new Inmanta project and environment using the inmanta-cli. ```bash # Go back to previous folder $ cd .. # Create a project called test $ inmanta-cli --host 172.30.0.3 project create -n test # Create an environment called lsm-srlinux $ inmanta-cli --host 172.30.0.3 environment create -p test -n lsm-srlinux --save ``` -------------------------------- ### Install a New Module in Editable Mode Source: https://github.com/inmanta/inmanta-core/blob/master/docs/model_developers/developer_getting_started.rst Install a newly created module in editable mode using pip. This allows changes in the module directory to be reflected immediately without reinstallation. ```bash pip install -e ./ ``` -------------------------------- ### Example project.yml configuration Source: https://github.com/inmanta/inmanta-core/blob/master/docs/model_developers/project_creation.rst Defines metadata for an Inmanta project, including name, description, author, module paths, and repository sources. Ensure careful consideration when using multiple Python package indexes due to security risks. ```yaml name: test description: a test project author: Inmanta author_email: code@inmanta.com license: ASL 2.0 copyright: 2020 Inmanta modulepath: libs downloadpath: libs repo: - url: https://github.com/inmanta/ type: git install_mode: release requires: pip: index-url: https://pypi.org/simple extra-index-url: [] pre: false use-system-config: false ``` -------------------------------- ### Create a Simple Plugin Source: https://github.com/inmanta/inmanta-core/blob/master/docs/model_developers/plugins.rst Define a basic plugin that prints a message and returns nothing. Place this code in your module's plugin directory (e.g., inmanta_plugins/example/__init__.py). ```python from inmanta.plugins import plugin @plugin def hello() -> None: print("Hello world!") ``` ```inmanta import example example::hello() ``` -------------------------------- ### Allocation V2 Native Example Source: https://github.com/inmanta/inmanta-core/blob/master/docs/lsm/allocation/allocation_v2.rst Demonstrates a use case where a single allocator is applied to both a service instance and an embedded entity. This example requires strict modifier enforcement to be enabled for setting read-only attributes on embedded entities. ```inmanta import lsm service first_value: int second_value: int third_value: int embedded entity fourth_value: int allocator MyAllocator def needs_allocation(self, context: ContextV2): # This method is called to check if allocation is needed # It should return a list of attribute names that need allocation return ["first_value", "second_value", "third_value", "embedded_entity::fourth_value"] def allocate(self, context: ContextV2): # This method performs the actual allocation # Values are set using context.set_value(name, value) context.set_value("first_value", 1) context.set_value("second_value", 2) context.set_value("third_value", 3) context.set_value("embedded_entity::fourth_value", 4) service_instance = service(first_value=0, second_value=0, third_value=0) service_instance.embedded_entity = service_instance.embedded_entity(fourth_value=0) alloc = MyAllocator() # The allocation process is handled by the framework, typically triggered by inmanta deploy # The following lines are for illustrative purposes and show how allocators are invoked: # context = ContextV2(service_instance) # alloc.needs_allocation(context) # alloc.allocate(context) ``` ```python from inmanta_plugins.lsm.allocation_v2.framework import ContextV2, AllocatorV2 class MyAllocator(AllocatorV2): def needs_allocation(self, context: ContextV2) -> list[str]: # This method is called to check if allocation is needed # It should return a list of attribute names that need allocation return ["first_value", "second_value", "third_value", "embedded_entity::fourth_value"] def allocate(self, context: ContextV2): # This method performs the actual allocation # Values are set using context.set_value(name, value) context.set_value("first_value", 1) context.set_value("second_value", 2) context.set_value("third_value", 3) context.set_value("embedded_entity::fourth_value", 4) ``` -------------------------------- ### External Inventory Deallocation Example Source: https://github.com/inmanta/inmanta-core/blob/master/docs/lsm/allocation/allocation.rst This example demonstrates how to handle de-allocation of resources using an external inventory. De-allocation is managed by a handler, ensuring that it is retried until successful. The handler for the PGAllocation entity is shown, focusing only on the delete operation. ```inmanta import inmanta.model @inmanta.model.entity("PGAllocation") class PGAllocation(inmanta.model.Resource): """Resource to manage VLAN ID allocation in an external PostgreSQL database.""" def __init__(self, name, service_instance, vlan_id=None, **kwargs): super().__init__(name, service_instance, **kwargs) self.vlan_id = vlan_id def get_id(self): return inmanta.types.Id(self.name) def get_allocation_key(self): return self.name def get_allocation_id(self): return self.vlan_id @inmanta.model.handler("PGAllocation") class PGAllocationHandler(inmanta.model.Handler): """Handler for PGAllocation resource, responsible for deallocation.""" def create_resource(self, resource): # Allocation is handled by a separate plugin, not here. raise NotImplementedError("Create operation not supported for PGAllocation") def update_resource(self, resource): # Updates are not supported for this resource type. raise NotImplementedError("Update operation not supported for PGAllocation") def delete_resource(self, resource): """Deallocates the VLAN ID from the external inventory.""" LOGGER.info("Deallocating VLAN ID %s for resource %s", resource.get_allocation_id(), resource.get_allocation_key()) # In a real implementation, this would interact with the external inventory to free the VLAN ID. # Example: self.plugin.delete(resource.get_allocation_key()) LOGGER.info("VLAN ID %s deallocated successfully.", resource.get_allocation_id()) ``` -------------------------------- ### Define Unidirectional Relation Source: https://github.com/inmanta/inmanta-core/blob/master/docs/language.rst Example of a unidirectional relation from Service to File. ```inmanta Service.file [1:] -- File ``` -------------------------------- ### Get Service Instance Configuration Source: https://github.com/inmanta/inmanta-core/blob/master/docs/lsm/index.rst Retrieves the configuration of a given service instance. ```APIDOC ## GET /lsm/v1/service_inventory///config ### Description Get the config of the service instance with id ``service_id``. ### Method GET ### Endpoint /lsm/v1/service_inventory///config ### Parameters #### Path Parameters - **service_entity** (string) - Required - The entity type of the service. - **service_id** (string) - Required - The unique identifier of the service instance. ### Response #### Success Response (200) - **config** (object) - The configuration object of the service instance. ``` -------------------------------- ### List Inmanta Projects Source: https://context7.com/inmanta/inmanta-core/llms.txt Lists all available Inmanta projects on the server. Requires specifying server host and port. ```bash # Point at a non-default server OPTS="--host inmanta.example.com --port 8888" # --- Projects --- inmanta-cli $OPTS project list ``` -------------------------------- ### Get Inmanta Parameter Source: https://context7.com/inmanta/inmanta-core/llms.txt Retrieves the value of a specific parameter from an Inmanta environment. ```bash inmanta-cli $OPTS param get -e --name db_host ``` -------------------------------- ### Modules Source: https://github.com/inmanta/inmanta-core/blob/master/docs/reference/api.rst Provides classes and functions for managing inmanta modules, including installation and metadata. ```APIDOC ## Modules ### InstallMode Represents the installation mode for modules. ### INSTALL_OPTS Options for module installation. ### InvalidModuleException Exception raised for invalid module configurations. ### InvalidMetadata Exception raised for invalid module metadata. ### ModuleLike Abstract base class for module-like objects. Provides `metadata` and `from_path`. ### Module Represents an inmanta module. Provides `from_path`, `get_plugin_files`, and `unload`. ### ModuleName Represents the name of a module. ### ModuleV1 Represents a module of version 1. ### ModuleV2 Represents a module of version 2. Provides `is_editable` and `from_path`. ### ModuleSource Provides methods for retrieving installed modules. ### ModuleV2Source Source for ModuleV2 objects. ### Path Represents a module path. ### PluginModuleFinder Finder for plugin modules. Provides `reset`. ### unload_inmanta_plugins Function to unload inmanta plugins. ``` -------------------------------- ### Define Bidirectional Relation Source: https://github.com/inmanta/inmanta-core/blob/master/docs/language.rst Example of a bidirectional relation between File and Service entities with specified multiplicities. ```inmanta File.service [1] -- Service.file [1:] ``` -------------------------------- ### Examples of Inmanta Function Calls Source: https://github.com/inmanta/inmanta-core/blob/master/docs/language.rst Demonstrates calling module functions like std::familyof and param::one. Also shows string replacement using positional and keyword arguments, including dictionary unpacking. ```inmanta std::familyof(host.os, "rhel") a = param::one("region", "demo::forms::AWSForm") hello_world = "Hello World!" hi_world = std::replace(hello_world, new = "Hi", old = "Hello") dct = { "new": "Hi", "old": "Hello", } hi_world = std::replace(hello_world, **dct) ``` -------------------------------- ### V2 Allocation Model Configuration Source: https://github.com/inmanta/inmanta-core/blob/master/docs/lsm/allocation/allocation_v3.rst Example of baseline V2 allocation configuration in an Inmanta model. ```inmanta import lsm # V2 allocation example service_a = ServiceA(name='service_a') service_b = ServiceB(name='service_b') # Allocate resources for service_a alloc_a = lsm::Allocator(service=service_a) alloc_a.allocate() # Allocate resources for service_b alloc_b = lsm::Allocator(service=service_b) alloc_b.allocate() ``` -------------------------------- ### Create Inmanta Project Source: https://context7.com/inmanta/inmanta-core/llms.txt Creates a new Inmanta project with a specified name. ```bash inmanta-cli $OPTS project create -n "my-infra" ```