Red Hat Training

A Red Hat training course is available for RHEL 8

Chapter 7. Introduction to Nmstate

Nmstate is a declarative network manager API. The nmstate package provides the libnmstate Python library and a command-line utility, nmstatectl, to manage NetworkManager on RHEL. When you use Nmstate, you describe the expected networking state using YAML or JSON-formatted instructions.

Using Nmstate has a lot of benefits. For example, it:

  • Provides a stable and extensible interface to manage RHEL network capabilities
  • Supports atomic and transactional operations at the host and cluster level
  • Supports partial editing of most properties and preserves existing settings that are not specified in the instructions
  • Provides plug-in support to enable administrators to use their own plug-ins

7.1. Using the libnmstate library in a Python application

The libnmstate Python library enables developers to use Nmstate in their own application

To use the library, import it in your source code:

import libnmstate

Note that you must install the nmstate package to use this library.

Example 7.1. Querying the network state using the libnmstate library

The following Python code imports the libnmstate library and displays the available network interfaces and their state:

import json
import libnmstate
from libnmstate.schema import Interface

net_state = libnmstate.show()
for iface_state in net_state[Interface.KEY]:
    print(iface_state[Interface.NAME] + ": "
          + iface_state[Interface.STATE])

7.2. Updating the current network configuration using nmstatectl

You can use the nmstatectl utility to store the current network configuration of one or all interfaces in a file. You can then use this file to:

  • Modify the configuration and apply it to the same system.
  • Copy the file to a different host and configure the host with the same or modified settings.

This procedure describes how to export the settings of the enp1s0 interface to a file, modify the configuration, and apply the settings to the host.

Prerequisites

  • The nmstate package is installed.

Procedure

  1. Export the settings of the enp1s0 interface to the ~/network-config.yml file:

    # nmstatectl show enp1s0 > ~/network-config.yml

    This command stores the configuration of enp1s0 in YAML format. To store the output in JSON format, pass the --json option to the command.

    If you do not specify an interface name, nmstatectl exports the configuration of all interfaces.

  2. Modify the ~/network-config.yml file using a text editor to update the configuration.
  3. Apply the settings from the ~/network-config.yml file:

    # nmstatectl set ~/network-config.yml

    If you exported the settings in JSON format, pass the --json option to the command.

7.3. Additional resources

  • /usr/share/doc/nmstate/README.md
  • /usr/share/doc/nmstate/examples/