Network Configuration

NetworkConfiguration

The ifup and ifdown commands may be used to configure (or, respectively, deconfigure) network interfaces based on interface definitions in the file /etc/network/interfaces.

/etc/network/interfaces

This contains network interface configuration information for the ifup and ifdown commands. This is where you configure how your system is connected to the network.

EXAMPLE


auto eth0
allow-hotplug eth1
iface eth0 inet dhcp
iface eth0 inet6 auto
iface eth1 inet static
	address 192.168.1.2/24
	gateway 192.168.1.1
iface eth1 inet6 static
	address fec0:0:0:1::2/64
	gateway fec0:0:0:1::1
The above example configures two network interfaces:
  • eth0
    • brought up at boot
    • uses DHCP for IPv4 and SLAAC for IPv6
  • eth1
    • brought up whenever the network hardware is detected
    • configured with static IPv4 and IPv6 addresses

HOOK SCRIPTS

There are four directories in which scripts can be placed which will always be run for any interface during certain phases of ifup and ifdown commands. These are:
  • /etc/network/if-pre-up.d/
  • Scripts in this directory are run before bringing the interface up.
  • /etc/network/if-up.d/
  • Scripts in this directory are run after bringing the interface up.
  • /etc/network/if-down.d/
  • Scripts in this directory are run before bringing the interface down.
  • /etc/network/if-post-down.d/
  • Scripts in this directory are run after bringing the interface down.

ENVIRONMENT VARIABLES

All hook scripts have access to the following environment variables:
  • IFACE
  • The physical name of the interface being processed, or "--all" (see below).
  • LOGICAL
  • The logical name of the interface being processed, or "auto" (see below).
  • ADDRFAM
  • The address family of the interface, or "meta" (see below).
  • METHOD
  • The method of the interface (e.g., static), or "none" (see below).
  • CLASS
  • The class of interfaces being processed. This is a copy of the value given to the --allow option when running ifup or ifdown, otherwise it is set to "auto" when the --all option is used.
  • MODE
  • start if run from ifup, stop if run from ifdown.
  • PHASE
  • As per MODE, but with finer granularity, distinguishing the pre-up, post-up, pre-down and post-down phases.
  • VERBOSITY
  • Indicates whether --verbose was used; set to 1 if so, 0 if not.
  • PATH
  • The command search path: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Additionally, all options given in an interface definition section are exported to the environment in upper case with "IF_" prepended and with hyphens converted to underscores and non-alphanumeric characters discarded.

Examples

For ex., the package "ethtool":
  • /etc/network/if-pre-up.d/ethtool
  • 
    #!/bin/sh
    
    ETHTOOL=/sbin/ethtool
    
    test -x $ETHTOOL || exit 0
    
    [ "$IFACE" != "lo" ] || exit 0
    
    # Gather together the mixed bag of settings applied with -s/--change
    SETTINGS="\
    ${IF_ETHERNET_PORT:+ port $IF_ETHERNET_PORT}\
    ${IF_DRIVER_MESSAGE_LEVEL:+ msglvl $IF_DRIVER_MESSAGE_LEVEL}\
    "
    [ -z "$SETTINGS" ] || $ETHTOOL --change "$IFACE" $SETTINGS
        
  • /etc/network/if-up.d/ethtool
  • 
    #!/bin/sh
    
    ETHTOOL=/sbin/ethtool
    
    test -x $ETHTOOL || exit 0
    
    [ "$IFACE" != "lo" ] || exit 0
    
    # Find settings with a given prefix and print them as they appeared in
    # /etc/network/interfaces, only with the prefix removed.
    # This actually prints each name and value on a separate line, but that
    # doesn't matter to the shell.
    gather_settings () {
        set | sed -n "
    /^IF_$1[A-Za-z0-9_]*=/ {
        h;                             # hold line
        s/^IF_$1//; s/=.*//; s/_/-/g;  # get name without prefix
        y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/;  # lower-case
        p;
        g;                             # restore line
        s/^[^=]*=//; s/^'\(.*\)'/\1/;  # get value
        p;
    }"
    }
    
    # Gather together the mixed bag of settings applied with -s/--change
    SETTINGS="\
    ${IF_LINK_SPEED:+ speed $IF_LINK_SPEED}\
    ${IF_LINK_DUPLEX:+ duplex $IF_LINK_DUPLEX}\
    "
    
    # WOL has an optional pass-key
    set -- $IF_ETHERNET_WOL
    SETTINGS="$SETTINGS${1:+ wol $1}${2:+ sopass $2}"
    
    # Autonegotiation can be on|off or an advertising mask
    case "$IF_ETHERNET_AUTONEG" in
    '')	;;
    on|off)	SETTINGS="$SETTINGS autoneg $IF_ETHERNET_AUTONEG" ;;
    *)	SETTINGS="$SETTINGS autoneg on advertise $IF_ETHERNET_AUTONEG" ;;
    esac
    
    [ -z "$SETTINGS" ] || $ETHTOOL --change "$IFACE" $SETTINGS
    
    SETTINGS="$(gather_settings ETHERNET_PAUSE_)"
    [ -z "$SETTINGS" ] || $ETHTOOL --pause "$IFACE" $SETTINGS
    
    SETTINGS="$(gather_settings HARDWARE_IRQ_COALESCE_)"
    [ -z "$SETTINGS" ] || $ETHTOOL --coalesce "$IFACE" $SETTINGS
    
    SETTINGS="$(gather_settings HARDWARE_DMA_RING_)"
    [ -z "$SETTINGS" ] || $ETHTOOL --set-ring "$IFACE" $SETTINGS
    
    SETTINGS="$(gather_settings OFFLOAD_)"
    [ -z "$SETTINGS" ] || $ETHTOOL --offload "$IFACE" $SETTINGS
      	
Other packages can make other options available for use in /etc/network/.

Netplan

The old way of configuring Debian-based network interfaces was based on the ifupdown package.
The new default is called Netplan.
Netplan is a utility for easily configuring networking on a linux system.
You simply create a YAML description file of the required network interfaces then all the necessary configuration for your chosen renderer tool will be generated by Netplan.

How does it work?

There are central network config files for Snappy, Server, Client, MaaS, cloud-init in /etc/netplan/*.yaml.
All installers only generate such a file, no /etc/network/interfaces any more.

Netplan reads network configuration files from /etc/netplan/*.yaml, during early boot, Netplan generates backend specific configuration files in /run to hand off control of devices to a particular networking daemon(renderers):

  • NetworkManager
  • This will make NetworkManager manage all devices (and by default, any ethernet device will come up with DHCP once carrier is detected).
    For ex., /etc/netplan/01-network-manager-all.yaml:
    
    # Let NetworkManager manage all devices on this system
    network:
      version: 2
      renderer: NetworkManager        
            
    The NetworkManager program itself is the same GUI-based interface configuration system.
  • Systemd-networkd
  • Using networkd as a renderer does not let devices automatically come up using DHCP; each interface needs to be specified in a file in /etc/netplan/* for its configuration.
    For ex., /etc/netplan/01-netcfg.yaml
    
    # This file describes the network interfaces available on your system
    # For more information, see netplan(5).
    network:
      version: 2
      renderer: networkd
      ethernets:
        enp0s31f6:
          dhcp4: yes    
        
    The above config tells of bringing up the Ethernet interface named enp0s31f6 via DHCP.
    Configuration is done with Netplan YAML files, but once "applied", Netplan creates the back-end configurations systemd requires.
A set of subcommands can be used to drive Netplan:
  • netplan generate
  • netplan generate converts netplan YAML into configuration files understood by the backends (systemd-networkd(8) or NetworkManager(8)). It does not apply the generated configuration.
    You will not normally need to run this directly as it is run by netplan apply, netplan try, or at boot.
    There are 3 locations that netplan generate considers:
    • /lib/netplan/*.yaml
    • /etc/netplan/*.yaml
    • /run/netplan/*.yaml
    /run/netplan is top priority, then /etc/netplan, with /lib/netplan having the lowest priority.
  • netplan apply
  • Apply all configuration files for the renderers, restarting them as necessary.
  • netplan try
  • Apply configuration and wait for user confirmation; will roll back if network is broken or no confirmation is given.

Netplan Design

Systems are configured during early boot with a “network renderer” which reads /etc/netplan/*.yaml and writes configuration to /run to hand off control of devices to the specified networking renderer(daemon).
  • Wifi and WWAN get managed by NetworkManager
  • Configured devices get handled by systemd-networkd by default
  • Unless explicitly marked as managed by a specific renderer (NetworkManager)
  • Devices not covered by the network config do not get touched at all.

netplan apply

netplan-apply - apply configuration from netplan YAML files to a running system.

The process works as follows:

  1. The backend configuration is generated from netplan YAML files.
  2. The appropriate backends (systemd-networkd(8) or NetworkManager(8)) are invoked to bring up configured interfaces.
  3. netplan apply iterates through interfaces that are still down, unbinding them from their drivers, and rebinding them.
  4. This gives udev(7) renaming rules the opportunity to run.
  5. If any devices have been rebound, the appropriate backends are re-invoked in case more matches can be done.
When networkd is used, netplan apply:
  
$ sudo systemctl status systemd-networkd
* systemd-networkd.service - Network Service
     Loaded: loaded (/lib/systemd/system/systemd-networkd.service; enabled-runtime; vendor preset: enabled)
     Active: active (running) since Mon 2022-04-18 01:35:56 UTC; 9min ago
       Docs: man:systemd-networkd.service(8)
   Main PID: 938 (systemd-network)
     Status: "Processing requests..."
      Tasks: 1 (limit: 1680)
     Memory: 1.2M
     CGroup: /system.slice/systemd-networkd.service
             `-938 /lib/systemd/systemd-networkd

Apr 18 01:35:56 ubuntu systemd[1]: Starting Network Service...
Apr 18 01:35:56 ubuntu systemd-networkd[938]: ens3: Gained IPv6LL
Apr 18 01:35:56 ubuntu systemd-networkd[938]: Enumeration completed
Apr 18 01:35:56 ubuntu systemd[1]: Started Network Service.
Apr 18 01:35:56 ubuntu systemd-networkd[938]: ens3: IPv6 successfully enabled
Apr 18 01:35:56 ubuntu systemd-networkd[938]: ens3: DHCPv4 address 10.0.2.15/24 via 10.0.2.2

Networkctl is a command line utility in the new release of systemd
  • To get the status information about your network links
  • 
    $ networkctl
    IDX LINK TYPE     OPERATIONAL SETUP     
      1 lo   loopback carrier     unmanaged 
      2 ens3 ether    routable    configured
    
    2 links listed.
        
  • To display information about the specified links, use the status command
  • 
    $ networkctl status ens3
    * 2: ens3                                                              
                 Link File: /usr/lib/systemd/network/99-default.link       
              Network File: /run/systemd/network/10-netplan-ens3.network   
                      Type: ether                                          
                     State: routable (configured)
         Alternative Names: enp0s3                                         
                      Path: pci-0000:00:03.0                               
                    Driver: virtio_net                                     
                    Vendor: Red Hat, Inc.                                  
                     Model: Virtio network device                          
                HW Address: 52:54:00:12:34:56                              
                       MTU: 1500 (min: 68, max: 65535)                     
      Queue Length (Tx/Rx): 1/1                                            
          Auto negotiation: no                                             
                     Speed: n/a                                            
                   Address: 10.0.2.15 (DHCP4)                              
                            fec0::5054:ff:fe12:3456                        
                            fe80::5054:ff:fe12:3456                        
                   Gateway: 10.0.2.2                                       
                            fe80::2                                        
                       DNS: 10.0.2.3                                       
         Activation Policy: up                                             
       Required For Online: yes       
        
  • 
          
        
  • 
          
        

General structure

A subset of the Networking Config Version 2 format defined for the netplan tool is upported by the cloud-init.

network:
  version: 2
  renderer: <RENDER>
  <TYPE>:
    <DEVICE CONFIGURATION ID>:
The network key has at least two required elements:
First it must include version: 2 and one or more of possible device types.
  • RENDER
  • networking backend for this definition
    • NetworkManager
    • networkd
  • TYPE
    • ethernets
    • wifis
    • modems
    • bonds
    • bridges
    Each type block contains device definitions for the “configuration IDs”.
  • DEVICE CONFIGURATION ID
  • The key names below the per-device-type definition maps (like ethernets:) are called “ID”s.
    They must be unique throughout the entire set of configuration files.
    Their primary purpose is to serve as anchor names for composite devices, each entry may include IP and/or device configuration.
Device can be virtual or physical device:
  • Virtual devices
  • These devices are being created by the protocol stack. (Examples: veth, bridge, bond)
  • Physical devices
  • These can dynamically come and go between reboots and even during runtime (hotplugging). (Examples: ethernet, wifi)
    They can be selected by “match:” rules.
    All specified properties for the match: key must match.
    The following properties for creating matches are supported:
    • name:
    • Current interface name.
    • macaddress:
    • Device’s MAC address in the form XX:XX:XX:XX:XX:XX.
    • driver:
    • Kernel driver name, corresponding to the DRIVER udev property.
    
    # all cards on second PCI bus
    match:
      name: enp2*
    
    # fixed MAC address
    match:
      macaddress: 11:22:33:AA:BB:FF
    
    # first card of driver ``ixgbe``
    match:
      driver: ixgbe
      name: en*s0        
            
    Match rules can be written so that they only match one device. Then the “set-name:” property can be used to give that device a more specific/desirable/nicer name than the default from udev’s ifnames.
    It is valid to specify no match rules at all, in which case the ID field is simply the interface name to be matched.

Netplan reference (Properties)

Common properties for all device types

  • dhcp4:
  • bool.
    Enable DHCP for IPv4. Off by default.
  • dhcp6:
  • bool.
    Enable DHCP for IPv6. Off by default.
  • addresses:
  • sequence of scalars.
    Add static addresses to the interface in addition to the ones received through DHCP or RA.
    Each sequence entry is in CIDR notation, i. e. of the form addr/prefixlen .
    • addr
    • is an IPv4 or IPv6 address as recognized by inet_pton(3)
    • prefixlen
    • the number of bits of the subnet.
    Example:
    
      	addresses: [192.168.14.2/24, 2001:1::1/64]
        
  • gateway4: or gateway6:
  • scalar. Set default gateway for IPv4/6, for manual address configuration. This requires setting addresses too. Gateway IPs must be in a form recognized by inet_pton(3).
    Example for IPv4:
    
      	gateway4: 172.16.0.1 Example for IPv6: gateway6: 2001:4::1
    	
  • mtu:
  • MTU SizeBytes.
    The MTU key represents a device’s Maximum Transmission Unit, the largest size packet or frame, specified in octets (eight-bit bytes), that can be sent in a packet- or frame-based network. Specifying mtu is optional.
  • nameservers:
  • mapping.
    Set DNS servers and search domains, for manual address configuration.
    There are two supported fields:
    • addresses:
    • is a list of IPv4 or IPv6 addresses similar to gateway*, and
    • search:
    • is a list of search domains.
    Example:
    
    nameservers:
      search: [lab, home]
      addresses: [8.8.8.8, FEDC::1]
    	
  • routes:
  • sequence of mapping).
    Add device specific routes. Each mapping includes a to, via key with an IPv4 or IPv6 address as value. metric is an optional value. Example:
    
    routes:
     - to: 0.0.0.0/0
       via: 10.23.2.1
       metric: 3
    	

Properties for modems:

GSM/CDMA modem configuration is only supported for the NetworkManager backend.
  • apn
  • scalar.
    Set the carrier APN (Access Point Name).
    This can be omitted if auto-config is enabled.
  • auto-config
  • bool.
    Specify whether to try and autoconfigure the modem by doing a lookup of the carrier against the Mobile Broadband Provider database.
    This may not work for all carriers.
  • device-id
  • scalar.
    Specify the device ID (as given by the WWAN management service) of the modem to match.
    This can be found using mmcli.
  • network-id
  • scalar.
    Specify the Network ID (GSM LAI format).
    If this is specified, the device will not roam networks.
  • number
  • scalar.
    The number to dial to establish the connection to the mobile broadband network. (Deprecated for GSM)
  • password
  • scalar.
    Specify the password used to authenticate with the carrier network.
    This can be omitted if auto-config is enabled.
  • pin
  • scalar.
    Specify the SIM PIN to allow it to operate if a PIN is set.
  • sim-id
  • scalar.
    Specify the SIM unique identifier (as given by the WWAN management service) which this connection applies to.
    If given, the connection will apply to any device also allowed by device-id which contains a SIM card matching the given identifier.
  • sim-operator-id
  • scalar.
    Specify the MCC/MNC string (such as “310260” or “21601”) which identifies the carrier that this connection should apply to.
    If given, the connection will apply to any device also allowed by device-id and sim-id which contains a SIM card provisioned by the given operator.
  • username
  • scalar.
    Specify the username used to authentiate with the carrier network.
    This can be omitted if auto-config is enabled.

Properties for wifis:

  • access-points:
  • Note that systemd-networkd does not natively support wifi:.
    This provides pre-configured connections to NetworkManager. The keys of the mapping are the SSIDs with the following supported properties:
    • password:
    • The network is assumed to be open.
    • mode:
      • infrastructure
      • The default mode.
      • ap
      • create an access point to which other devices can connect.
      • adhoc
      • Connect to peer to peer networks without a central access point.
      • mesh
    • bssid:
    • only associate with the given BSSID
    • band:
      • 5GHz
      • 2.4GHz
      Do not restrict the 802.11 frequency band of the network if unset (the default).
    • channel:
    • This property takes effect only if the band property is also set.
    • hidden:
      • Set to true for connecting to hidden WiFi networks.
      • Set to false (the default) for connecting to publicly broadcast SSIDs.
  • wakeonwlan:
  • This enables WakeOnWLan on supported devices.

Properties for bonds:

Network bonding is a way to combine multiple physical ports programmatically so that they act as one.
There are two reasons: throughput and fault tolerence.

  • interfaces:
  • Sequence of scalars.
    All devices matching this ID list will be added to the bond.
    Example,
    
    ethernets:
      switchports:
        match: {name: "enp2*"}
    [...]
    bonds:
      bond0:
        interfaces: [switchports]        
            
  • parameters
  • Customization parameters for special bonding options.
    Time values are specified in seconds unless otherwise specified.
    • mode
    • scalar.
      Set the bonding mode used for the interfaces. Possible values are
      • balance-rr
      • The default is balance-rr (round robin).
        Round-robin policy: Transmit packets in order from the first available interface to the last.
        This mode provides load balancing and fault tolerance.
      • active-backup
      • Active-backup policy: Only one interface in the bond is active.
        A different interface becomes active if, and only if, the active interface fails.
        The bond's MAC address is externally visible on only one port (network adapter) to avoid confusing the switch. This mode provides fault tolerance.
      • balance-xor
      • XOR policy: Transmit based on selectable hashing algorithm.
        The default policy is a simple source+destination MAC address algorithm.
        Alternate transmit policies may be selected via the xmit_hash_policy option, described below.
        This mode provides load balancing and fault tolerance.
      • broadcast
      • Broadcast policy: transmits everything on all interfaces. This mode provides fault tolerance.
      • 802.3ad
      • IEEE 802.3ad Dynamic link aggregation.
        Creates aggregation groups that share the same speed and duplex settings.
        Utilizes all interfaces in the active aggregator according to the 802.3ad specification.
      • balance-tlb
      • Adaptive transmit load balancing: channel bonding that does not require any special switch support. The outgoing traffic is distributed according to the current load (computed relative to the speed) on each interface. Incoming traffic is received by the current interface. If the receiving interface fails, another interface takes over the MAC address of the failed receiving interface.
      • balance-alb
      • Adaptive load balancing: includes balance-tlb plus receive load balancing (rlb) for IPV4 traffic, and does not require any special switch support. The receive load balancing is achieved by ARP negotiation. The bonding driver intercepts the ARP Replies sent by the local system on their way out and overwrites the source hardware address with the unique hardware address of one of the interfaces in the bond such that different peers use different hardware addresses for the server.
    • lacp-rate
    • Set the rate at which LACPDUs are transmitted. This is only useful in 802.3ad mode.
      Possible values are slow (30 seconds, default), and fast (every second).
    • mii-monitor-interval
    • Specifies the interval for MII monitoring (verifying if an interface of the bond has carrier).
    • min-links
    • The minimum number of links up in a bond to consider the bond interface to be up.
    • transmit-hash-policy
    • Specifies the transmit hash policy for the selection of slaves.
      This is only useful in balance-xor, 802.3ad and balance-tlb modes.
      Possible values are layer2, layer3+4, layer2+3, encap2+3, and encap3+4.
    • ad-select
    • Set the aggregation selection mode.
      Possible values are stable, bandwidth, and count.
      This option is only used in 802.3ad mode.
    • all-slaves-active
    • bool.
      If the bond should drop duplicate frames received on inactive ports, set this option to false. If they should be delivered, set this option to true.
      The default value is false, and is the desirable behavior in most situations.
    • primary
    • Specify a device to be used as a primary slave, or preferred device to use as a slave for the bond (ie. the preferred device to send data through), whenever it is available.
      This only affects active-backup, balance-alb, and balance-tlb modes.
For ex.,

network:
  version: 2
  renderer: networkd
  ethernets:
    enp13s0:
      #Disables DHCP for the interface.
      dhcp4: no
      #Optional option allows for this interface to be disabled without breaking the bond.
      optional: true
    enp0s31f6:
      #Disables DHCP for the interface.
      dhcp4: no
      #Optional option allows for this interface to be disabled without breaking the bond.
      optional: true
  bonds:
    bond4:
      interfaces:
        - enp13s0
        - enp0s31f6
      parameters:
        mode: active-backup
        mii-monitor-interval: 1
      dhcp4: true
  

Netplan configuration examples

Configuration

To configure netplan,
  • save configuration files under /etc/netplan/ with a .yaml extension
  • For e.g., /etc/netplan/01-network-manager-all.yaml:
    
    # Let NetworkManager manage all devices on this system
    network:
      version: 2
      renderer: NetworkManager 
        
  • applie the configuration to the system
  • 
    $ sudo netplan apply
        

Examples

  • Using DHCP and static addressing
  • 
    network:
        version: 2
        renderer: networkd
        ethernets:
            enp3s0:
                dhcp4: true    
            enp3s1:
                addresses:
                    - 10.10.10.2/24
                gateway4: 10.10.10.1
                nameservers:
                    search: [mydomain, otherdomain]
                    addresses: [10.10.10.1, 1.1.1.1]            
        
  • Connecting multiple interfaces with DHCP
  • 
    network:
        version: 2
        ethernets:
            enred:
                dhcp4: yes
                dhcp4-overrides:
                    route-metric: 100
            engreen:
                dhcp4: yes
                dhcp4-overrides:
                    route-metric: 200    
        
    To achieve the exact routing desired over DHCP by specifying a metric.
  • Using Network Manager as a renderer
  • 
    network:
        version: 2
        renderer: NetworkManager
        
  • Connecting to an open wireless network
  • 
    network:
        version: 2
        wifis:
            wl0:
                access-points:
                    opennetwork: {}
                dhcp4: yes    
        
  • Connecting to a WPA Personal wireless network
  • 
    network:
        version: 2
        renderer: networkd
        wifis:
            wlp2s0b1:
                dhcp4: no
                dhcp6: no
                addresses: [192.168.0.21/24]
                gateway4: 192.168.0.1
                nameservers:
                    addresses: [192.168.0.1, 8.8.8.8]
                access-points:
                    "network_ssid_name":
                        password: "**********"
        
        
  • Using multiple addresses on a single interface
  • 
    network:
        version: 2
        renderer: networkd
        ethernets:
            enp3s0:
             addresses:
                 - 10.100.1.38/24
                 - 10.100.1.39/24
             gateway4: 10.100.1.1    
        
  • Configuring interface bonding
  • Bonding is configured by declaring a bond interface with a list of physical interfaces and a bonding mode.
    Below is an example of an active-backup bond that uses DHCP to obtain an address:
    
    network:
        version: 2
        renderer: networkd
        bonds:
            bond0:
                dhcp4: yes
                interfaces:
                    - enp3s0
                    - enp4s0
                parameters:
                    mode: active-backup
                    primary: enp3s0    
        

Network Manager

NetworkManager is a program for providing detection and configuration for systems to automatically connect to networks.
NetworkManager's functionality can be useful for both wireless and wired networks.
For wireless networks, NetworkManager prefers known wireless networks and has the ability to switch to the most reliable network.
NetworkManager also prefers wired connections over wireless ones, has support for modem connections and certain types of VPN.
NetworkManager was originally developed by Red Hat and now is hosted by the GNOME project.

Installation

NetworkManager can be installed with the package networkmanager, which contains
  • a daemon
  • a command line interface (nmcli)
  • a curses‐based interface (nmtui)
After installation, you should use systemctl to start/enable NetworkManager.service. You must ensure that no other service that wants to configure the network is running. You can find a list of the currently running services with:

systemctl --type=service
Except for the Ethernet networking support,
  • Mobile broadband support
  • Install modemmanager, mobile-broadband-provider-info and usb_modeswitch packages for mobile broadband connection support. See USB 3G Modem#NetworkManager for details.
  • PPPoE / DSL support
  • Install rp-pppoe package for PPPoE / DSL connection support.
    To actually add PPPoE connection, use nm-connection-editor and add new DSL/PPPoE connection.
  • VPN support
  • NetworkManager since version 1.16 has native support for WireGuard, all it needs is the wireguard kernel module.
    Support for other VPN types is based on a plug-in system.

Control

The basic format of a nmcli command is as follows:

nmcli [OPTIONS] OBJECT { COMMAND | help }
where OBJECT can be one of the following options:
  • general
  • networking
  • radio
  • connection
  • device
  • agent
  • monitor
nmcli examples:
  • List nearby Wi-Fi networks:
  • 
    $ nmcli device wifi list
    	
  • Connect to a Wi-Fi network:
  • 
    $ nmcli device wifi connect SSID_or_BSSID password password
    	
  • Connect to a hidden Wi-Fi network:
  • 
    $ nmcli device wifi connect SSID_or_BSSID password password hidden yes
    	
  • Connect to a Wi-Fi on the wlan1 interface:
  • 
    $ nmcli device wifi connect SSID_or_BSSID password password ifname wlan1 profile_name
    	
  • Disconnect an interface:
  • 
    $ nmcli device disconnect ifname eth0
    	
  • Get a list of connections with their names, UUIDs, types and backing devices:
  • 
    $ nmcli connection show
    	
  • Activate a connection (i.e. connect to a network with an existing profile):
  • 
    $ nmcli connection up name_or_uuid
    	
  • Delete a connection:
  • 
    $ nmcli connection delete name_or_uuid
    	
  • See a list of network devices and their state:
  • 
    $ nmcli device
    	
  • Turn off Wi-Fi:
  • 
    $ nmcli radio wifi off
    	

Configuration

All the connection configuration files will be stored under /etc/NetworkManager:

├── conf.d
│   ├── 10-ubuntu-fan.conf
│   └── default-wifi-powersave-on.conf
├── dispatcher.d
│   ├── 01-ifupdown
│   ├── no-wait.d
│   ├── pre-down.d
│   └── pre-up.d
├── dnsmasq.d
├── dnsmasq-shared.d
├── NetworkManager.conf
└── system-connections
    ├── Jerry_DSL-5G.nmconnection
    └── tw-jerry-lee-tpe@2.nmconnection
  • the global default configuration
  • NetworkManager has a global configuration file at /etc/NetworkManager/NetworkManager.conf.
    
    [main]
    plugins=ifupdown,keyfile
    
    [ifupdown]
    managed=false
    
    [device]
    wifi.scan-rand-mac-address=no
    	
    Usually no configuration needs to be done to the global defaults.

    After editing a configuration file, the changes can be applied by running:

    
    # nmcli general reload
    	
  • Additional configuration files
  • /etc/NetworkManager/conf.d/

DHCP client

By default NetworkManager uses its internal DHCP client.
To change the DHCP client backend, set the option main.dhcp=dhcp_client_name with a configuration file in /etc/NetworkManager/conf.d/.
For ex., /etc/NetworkManager/conf.d/dhcp-client.conf:

[main]
dhcp=dhclient

DNS management

NetworkManager's DNS management is described in the GNOME project's wiki page—Projects/NetworkManager/DNS.

Network services with NetworkManager dispatcher

NetworkManager has the ability to start services when you connect to a network and stop them when you disconnect (e.g. when using NFS, SMB and NTPd).
To activate the feature you need to enable and start the NetworkManager-dispatcher.service.
Once the service is active, scripts can be added to the /etc/NetworkManager/dispatcher.d directory.
The scripts will be run in alphabetical order at connection time, and in reverse alphabetical order at disconnect time.
Scripts will receive the following arguments in order:
  1. Interface name
  2. e.g. eth0
  3. Interface status
  4. up or down
  5. VPN status
  6. vpn-up or vpn-down
For ex., to use dispatcher to automatically toggle wireless depending on LAN cable being plugged in.
The idea is to only turn Wi-Fi on when the LAN cable is unplugged (for example when detaching from a laptop dock), and for Wi-Fi to be automatically disabled, once a LAN cable is plugged in again.
Create the following dispatcher script, replacing enp3s0 with yours.:

#!/bin/sh

if [ "$1" = "enp3s0" ]; then
    case "$2" in
        up)
            nmcli radio wifi off
            ;;
        down)
            nmcli radio wifi on
            ;;
    esac
fi

Tips and tricks

  • Encrypted Wi-Fi passwords
  • By default, NetworkManager stores passwords in clear text in the connection files at /etc/NetworkManager/system-connections/.
    
    $ sudo grep -r '^psk=' /etc/NetworkManager/system-connections/
    /etc/NetworkManager/system-connections/Jerry_DSL-5G.nmconnection:psk=***
        
    It's possible to save the passwords in encrypted form in a keyring instead of clear text. The downside of using a keyring is that the connections have to be set up for each user.
  • Sharing internet connection over Wi-Fi
  • You can share your internet connection (e.g. 3G or wired) to WiFi.
    You will need:
    • A Wi-Fi card which supports AP mode
    • You need a nl80211 compatible wireless device, which supports the AP operating mode:
      
      $ iw list
      ...
      	Supported interface modes:
      		 * IBSS
      		 * managed
      		 * AP
      		 * AP/VLAN
      		 * monitor
      		 * mesh point
      		 * P2P-client
      		 * P2P-GO
      ...    
          	
    • Enable hotspot
    • wpa_supplicant has a "lightweight hotspot" mode that NetworkManager will utilize.
      NetworkManager checks if the wifi card supports AP mode, so the rest of the job is to push the correct configuration options to wpa_supplicant when Internet Connection Sharing is started.
      NetworkManager now supports an enhanced Hotspot/Internet Connection Sharing mode for WiFi, which enables a much smoother connection sharing experience and is better supported by hardware.
    • Install the dnsmasq package to be able to actually share the connection
    • To see if dnsmasq started properly, check the system's journal:
      
      $ sudo journalctl -u dnsmasq.service
      -- Logs begin at Fri 2022-03-04 03:12:14 UTC, end at Sat 2022-03-05 08:51:40 UTC. --
      -- No entries --
            
  • Sharing internet connection over Ethernet
  • You want to share the internet connection on WiFi to other devices over ethernet.
    Install the dnsmasq package to be able to actually share the connection
  • Checking if networking is up inside a cron job or script
  • Add an if test for networking that uses nmcli and checks the state of networking.
    
    nmcli device > nmcli.log
    cat nmcli.log | while read line
        do
           TYPE=$( echo $line | cut -f2 -d" " )
           if [ $TYPE == "wifi" ]; then
              STATE=$( echo $line | cut -f3 -d" " )
              if [ $STATE == "connected" ]; then
                 echo "WiFi is connected"
                 # Whatever you want to do if the network is online
              else
                 echo "WiFi is not connected"
                 # Whatever you want to do if the network is offline
              fi
           fi
        done
        
  • Ignore specific devices
  • You can quickly and easily ignore devices by MAC or interface-name by using the following in /etc/NetworkManager/conf.d/unmanaged.conf:
    
    [keyfile]
    unmanaged-devices=mac:00:22:68:1c:59:b1;mac:00:1E:65:30:D1:C4;interface-name:eth0
        

Debug NetworkManager

NetworkManager provides different levels and domains to produce logging information.

Viewing NetworkManager logs


# journalctl -u NetworkManager -b
Increasing the log levels for all or certain domains helps to log more details of the operations NetworkManager performs.
  • The level defines the verbosity level
  • One of OFF, ERR, WARN, INFO, DEBUG, TRACE.
  • The domain define the category of the messages to be logged with given level
  • The following log domains are available: PLATFORM, RFKILL, ETHER, WIFI, BT, MB, DHCP4, DHCP6, PPP, WIFI_SCAN, IP4, IP6, AUTOIP4, DNS, VPN, SHARING, SUPPLICANT, AGENTS, SETTINGS, SUSPEND, CORE, DEVICE, OLPC, WIMAX, INFINIBAND, FIREWALL, ADSL, BOND, VLAN, BRIDGE, DBUS_PROPS, TEAM, CONCHECK, DCB, DISPATCH, AUDIT, SYSTEMD, VPN_PLUGIN, PROXY.
By default, all the log domains are set to record the INFO log level.

You can change the log level at run time using nmcli.

  • Display the current logging settings
  • 
    $ nmcli general logging    
    LEVEL  DOMAINS                                                                                                    
     
    INFO   PLATFORM,RFKILL,ETHER,WIFI,BT,MB,DHCP4,DHCP6,PPP,IP4,IP6,AUTOIP4,DNS,VPN,SHARING,SUPPLICANT,AGENTS,SETTINGS
    ,SUSPEND,CORE,DEVICE,OLPC,INFINIBAND,FIREWALL,ADSL,BOND,VLAN,BRIDGE,TEAM,CONCHECK,DCB,DISPATCH,AUDIT,SYSTEMD,PROXY
        
  • To set the log level for all domains to the same LEVEL
  • 
    # nmcli general logging level LEVEL domains ALL
        
  • To change the level for specific domains
  • 
    # nmcli general logging level LEVEL domains DOMAINS 
        
    For ex., the snap.network-manager.networkmanager.service:
    
    $ sudo nmcli general logging level TRACE domain WIFI
    $ sudo journalctl -u snap.network-manager.networkmanager -b
        
  • To change the level of specific domains and preserve the level of all other domains
  • 
    # nmcli general logging level KEEP domains DOMAIN:LEVEL,DOMAIN:LEVEL    
        
But, updating debugging levels and domains using the /etc/NetworkManager/NetworkManager.conf file helps to debug boot issues and captures all the logs from the initial state.

Troubleshooting

  • Network management disabled
  • When NetworkManager shuts down but the pid (state) file is not removed, you will see a Network management disabled message. If this happens, remove the file manually:
    
    # rm /var/lib/NetworkManager/NetworkManager.state
        



nm-settings

NetworkManager is based on a concept of connection profiles, sometimes referred to as connections only.
The connection profiles are handled by NetworkManager via settings service and are exported on D-Bus.
  • Connection (profile)
  • A specific, encapsulated, independent group of settings describing all the configuration required to connect to a specific network.
    It is referred to by a unique identifier called the UUID.
  • Setting
  • A group of related key/value pairs describing a specific piece of a Connection (profile).
Users are free to create as many connection profiles as they see fit. Thus they are flexible in having various network configurations for different networking needs.

Settings keys(properties) and allowed values are described in the tables below.

  • 802-11-wireless setting

Key NameValue TypeDefault ValueValue Description
bandstring 802.11 frequency band of the network. One of "a" for 5GHz 802.11a or "bg" for 2.4GHz 802.11. This will lock associations to the Wi-Fi network to the specific band, i.e. if "a" is specified, the device will not associate with the same network in the 2.4GHz band even if the network's settings are compatible. This setting depends on specific driver capability and may not work with all drivers.
bssidbyte array If specified, directs the device to only associate with the given access point. This capability is highly driver dependent and not supported by all devices. Note: this property does not control the BSSID used when creating an Ad-Hoc network and is unlikely to in the future.
channeluint320Wireless channel to use for the Wi-Fi connection. The device will only join (or create for Ad-Hoc networks) a Wi-Fi network on the specified channel. Because channel numbers overlap between bands, this property also requires the "band" property to be set.
cloned-mac-addressbyte array If specified, request that the Wi-Fi device use this MAC address instead of its permanent MAC address. This is known as MAC cloning or spoofing.
hiddenbooleanFALSEIf TRUE, indicates this network is a non-broadcasting network that hides its SSID. In this case various workarounds may take place, such as probe-scanning the SSID for more reliable network discovery. However, these workarounds expose inherent insecurities with hidden SSID networks, and thus hidden SSID networks should be used with caution.
mac-addressbyte array If specified, this connection will only apply to the Wi-Fi device whose permanent MAC address matches. This property does not change the MAC address of the device (i.e. MAC spoofing).
mac-address-blacklistarray of string[]A list of permanent MAC addresses of Wi-Fi devices to which this connection should never apply. Each MAC address should be given in the standard hex-digits-and-colons notation (eg "00:11:22:33:44:55").
mac-address-randomizationuint320One of NM_SETTING_MAC_RANDOMIZATION_DEFAULT (0) (never randomize unless the user has set a global default to randomize and the supplicant supports randomization), NM_SETTING_MAC_RANDOMIZATION_NEVER (1) (never randomize the MAC address), or NM_SETTING_MAC_RANDOMIZATION_ALWAYS (2) (always randomize the MAC address).
modestring Wi-Fi network mode; one of "infrastructure", "adhoc" or "ap". If blank, infrastructure is assumed.
mtuuint320If non-zero, only transmit packets of the specified size or smaller, breaking larger packets up into multiple Ethernet frames.
namestring802-11-wirelessThe setting's name, which uniquely identifies the setting within the connection. Each setting type has a name unique to that type, for example "ppp" or "wireless" or "wired".
powersaveuint320One of NM_SETTING_WIRELESS_POWERSAVE_DISABLE (2) (disable Wi-Fi power saving), NM_SETTING_WIRELESS_POWERSAVE_ENABLE (3) (enable Wi-Fi power saving), NM_SETTING_WIRELESS_POWERSAVE_IGNORE (1) (don't touch currently configure setting) or NM_SETTING_WIRELESS_POWERSAVE_DEFAULT (0) (use the globally configured value). All other values are reserved.
rateuint320If non-zero, directs the device to only use the specified bitrate for communication with the access point. Units are in Kb/s, ie 5500 = 5.5 Mbit/s. This property is highly driver dependent and not all devices support setting a static bitrate.
securityNone This property is deprecated, but can be set to the value '802-11-wireless-security' when a wireless security setting is also present in the connection dictionary, for compatibility with very old NetworkManager daemons.
seen-bssidsarray of string[]A list of BSSIDs (each BSSID formatted as a MAC address like "00:11:22:33:44:55") that have been detected as part of the Wi-Fi network. NetworkManager internally tracks previously seen BSSIDs. The property is only meant for reading and reflects the BSSID list of NetworkManager. The changes you make to this property will not be preserved.
ssidbyte array SSID of the Wi-Fi network. Must be specified.
tx-poweruint320If non-zero, directs the device to use the specified transmit power. Units are dBm. This property is highly driver dependent and not all devices support setting a static transmit power.


    • mode
    • src/libnm-core-public/nm-setting-wireless.h:
      
      #define NM_SETTING_WIRELESS_MODE_INFRA "infrastructure"
      #define NM_SETTING_WIRELESS_MODE_ADHOC "adhoc"
      #define NM_SETTING_WIRELESS_MODE_AP "ap"
      #define NM_SETTING_WIRELESS_MODE_MESH "mesh"        
              	
      • infrastructure
      • Indicates infrastructure mode where an access point is expected to be present for this connection.
      • ap
      • Indicates AP/master mode where the wireless device is started as an access point/hotspot.
      • adhoc
      • Indicates Ad-Hoc mode where no access point is expected to be present.
      • mesh
      • Indicates that the connection should create a mesh point.
  • 802-11-wireless-security setting
 
Key NameValue TypeDefault ValueValue Description
auth-algstring When WEP is used (ie, key-mgmt = "none" or "ieee8021x") indicate the 802.11 authentication algorithm required by the AP here. One of "open" for Open System, "shared" for Shared Key, or "leap" for Cisco LEAP. When using Cisco LEAP (ie, key-mgmt = "ieee8021x" and auth-alg = "leap") the "leap-username" and "leap-password" properties must be specified.
grouparray of string[]A list of group/broadcast encryption algorithms which prevents connections to Wi-Fi networks that do not utilize one of the algorithms in the list. For maximum compatibility leave this property empty. Each list element may be one of "wep40", "wep104", "tkip", or "ccmp".
key-mgmtstring Key management used for the connection. One of "none" (WEP), "ieee8021x" (Dynamic WEP), "wpa-none" (Ad-Hoc WPA-PSK), "wpa-psk" (infrastructure WPA-PSK), or "wpa-eap" (WPA-Enterprise). This property must be set for any Wi-Fi connection that uses security.
leap-passwordstring The login password for legacy LEAP connections (ie, key-mgmt = "ieee8021x" and auth-alg = "leap").
leap-password-flagsNMSettingSecretFlags (uint32) Flags indicating how to handle the "leap-password" property. (see the section called “Secret flag types:” for flag values)
leap-usernamestring The login username for legacy LEAP connections (ie, key-mgmt = "ieee8021x" and auth-alg = "leap").
namestring802-11-wireless-securityThe setting's name, which uniquely identifies the setting within the connection. Each setting type has a name unique to that type, for example "ppp" or "wireless" or "wired".
pairwisearray of string[]A list of pairwise encryption algorithms which prevents connections to Wi-Fi networks that do not utilize one of the algorithms in the list. For maximum compatibility leave this property empty. Each list element may be one of "tkip" or "ccmp".
protoarray of string[]List of strings specifying the allowed WPA protocol versions to use. Each element may be one "wpa" (allow WPA) or "rsn" (allow WPA2/RSN). If not specified, both WPA and RSN connections are allowed.
pskstring Pre-Shared-Key for WPA networks. If the key is 64-characters long, it must contain only hexadecimal characters and is interpreted as a hexadecimal WPA key. Otherwise, the key must be between 8 and 63 ASCII characters (as specified in the 802.11i standard) and is interpreted as a WPA passphrase, and is hashed to derive the actual WPA-PSK used when connecting to the Wi-Fi network.
psk-flagsNMSettingSecretFlags (uint32) Flags indicating how to handle the "psk" property. (see the section called “Secret flag types:” for flag values)
wep-key-flagsNMSettingSecretFlags (uint32) Flags indicating how to handle the "wep-key0", "wep-key1", "wep-key2", and "wep-key3" properties. (see the section called “Secret flag types:” for flag values)
wep-key-typeNMWepKeyType (uint32) Controls the interpretation of WEP keys. Allowed values are NM_WEP_KEY_TYPE_KEY (1), in which case the key is either a 10- or 26-character hexadecimal string, or a 5- or 13-character ASCII password; or NM_WEP_KEY_TYPE_PASSPHRASE (2), in which case the passphrase is provided as a string and will be hashed using the de-facto MD5 method to derive the actual WEP key.
wep-key0string Index 0 WEP key. This is the WEP key used in most networks. See the "wep-key-type" property for a description of how this key is interpreted.
wep-key1string Index 1 WEP key. This WEP index is not used by most networks. See the "wep-key-type" property for a description of how this key is interpreted.
wep-key2string Index 2 WEP key. This WEP index is not used by most networks. See the "wep-key-type" property for a description of how this key is interpreted.
wep-key3string Index 3 WEP key. This WEP index is not used by most networks. See the "wep-key-type" property for a description of how this key is interpreted.
wep-tx-keyidxuint320When static WEP is used (ie, key-mgmt = "none") and a non-default WEP key index is used by the AP, put that WEP key index here. Valid values are 0 (default key) through 3. Note that some consumer access points (like the Linksys WRT54G) number the keys 1 - 4.

List all the setting's configuration of a connection(interface):

$ nmcli c
NAME                 UUID                                  TYPE      DEVICE 
netplan-wlan0-guest  abc5d1b3-dc99-3148-821e-ea5f6d253dd5  wifi      wlan0  
netplan-all-en       5ed20450-f673-31b9-a57a-c0737409da91  ethernet  --     
netplan-all-eth      bd1f2e72-56d1-3145-b8ff-9a2f9b07daed  ethernet  --   

$ nmcli c show netplan-wlan0-guest
connection.id:                          netplan-wlan0-guest
...
802-11-wireless.ssid:                   guest
802-11-wireless.mode:                   ap
802-11-wireless.band:                   --
802-11-wireless.channel:                0
802-11-wireless.bssid:                  --
802-11-wireless.rate:                   0
802-11-wireless.tx-power:               0
802-11-wireless.mac-address:            --
802-11-wireless.cloned-mac-address:     --
802-11-wireless.generate-mac-address-mask:--
802-11-wireless.mac-address-blacklist:  --
802-11-wireless.mac-address-randomization:default
802-11-wireless.mtu:                    auto
802-11-wireless.seen-bssids:            00:90:4C:C5:12:38
802-11-wireless.hidden:                 no
802-11-wireless.powersave:              0 (default)
802-11-wireless.wake-on-wlan:           0x1 (default)
802-11-wireless-security.key-mgmt:      wpa-psk
802-11-wireless-security.wep-tx-keyidx: 0
802-11-wireless-security.auth-alg:      --
802-11-wireless-security.proto:         --
802-11-wireless-security.pairwise:      --
802-11-wireless-security.group:         --
802-11-wireless-security.pmf:           0 (default)
802-11-wireless-security.leap-username: --
802-11-wireless-security.wep-key0:      <hidden>
802-11-wireless-security.wep-key1:      <hidden>
802-11-wireless-security.wep-key2:      <hidden>
802-11-wireless-security.wep-key3:      <hidden>
802-11-wireless-security.wep-key-flags: 0 (none)
802-11-wireless-security.wep-key-type:  unknown
802-11-wireless-security.psk:           <hidden>
802-11-wireless-security.psk-flags:     0 (none)
802-11-wireless-security.leap-password: <hidden>
802-11-wireless-security.leap-password-flags:0 (none)
802-11-wireless-security.wps-method:    0x0 (default)
802-11-wireless-security.fils:          0 (default)
ipv4.method:                            shared
...

Configuring networking with nmcli

It is recommended to type a partial nmcli command, and then press the Tab key to auto-complete the command sequence. If multiple completions are possible, then Tab lists them all. Fox ex.,

$ nmcli 
con  dev  nm   
$ nmcli con 
delete  down    list    status  up        
  

Overview of nmcli property names and aliases

systemd.network - Network configuration

The main network file must have the extension .network; other extensions are ignored.
The .network files are read from the files located in the system network directory /lib/systemd/network and the volatile runtime network directory /run/systemd/network and the local administration network directory /etc/systemd/network:
  • /run/systemd/network
  • 
    ├── 73-usb-net-by-mac.link
    ├── 80-container-host0.network
    ├── 80-container-ve.network
    ├── 80-container-vz.network
    ├── 80-wifi-adhoc.network
    ├── 80-wifi-ap.network.example
    ├── 80-wifi-station.network.example
    └── 99-default.link
       
  • All configuration files are collectively sorted and processed in lexical order, regardless of the directories in which they live.
  • Files in /etc have the highest priority, files in /run take precedence over files with the same name in /lib.
  • This can be used to override a system-supplied configuration file with a local file if needed.
If Ubuntu is installed in server mode, it is almost certainly configured to use networkd as the back end.

SystemdNetworkd

Setting up Systemd-Networkd

If you currently have a network running using /etc/network/, move the interfaces file there to another name so that it won't be used after systemd-networkd is set up:

mv /etc/network/interfaces /etc/network/interfaces.save
  • basic configuration
    • enable systemd-networkd
    • 
      # systemctl status systemd-networkd
      ● systemd-networkd.service - Network Service
           Loaded: loaded (/usr/lib/systemd/system/systemd-networkd.service; disabled;
       vendor preset: enabled)
           Active: inactive (dead)
             Docs: man:systemd-networkd.service(8)
      
      # systemctl enable systemd-networkd
      Created symlink /etc/systemd/system/dbus-org.freedesktop.network1.service → /usr/lib/systemd/system/systemd-networkd.service.
      Created symlink /etc/systemd/system/multi-user.target.wants/systemd-networkd.service → /usr/lib/systemd/system/systemd-networkd.service.
      Created symlink /etc/systemd/system/sockets.target.wants/systemd-networkd.socket → /usr/lib/systemd/system/systemd-networkd.socket.
      Created symlink /etc/systemd/system/network-online.target.wants/systemd-networkd-wait-online.service → /usr/lib/systemd/system/systemd-networkd-wait-online. 
        	
      All configuration files are generally stored in /etc/systemd/network.
    • define a network
    • Add a *.network file in /etc/systemd/network:
      • DHCP
      • 
          [Match]
          Name=eth0
        
          [Network]
          DHCP=ipv4
        	
      • static IP
      • [Match] Name=enp8s0 [Network] Address=192.168.1.20/24 Gateway=192.168.1.1 DNS=192.168.1.1
  • beyond the basics
  • Setting up a network bridge:
    • define the virtual network device using a br0.netdev file in /etc/systemd/network/
    • 
        [NetDev]
        Name=br0
        Kind=bridge
        MACAddress=xx:xx:xx:xx:xx:xx  
      		
    • define the real network device using br0.network file in /etc/systemd/network/ to link the virtual device
    • 
        [Match]
        Name=eth0
      
        [Network]
        Bridge=br0
      		
    • define the IP network using lan0.network file in /etc/systemd/network/
    • 
        [Match]
        Name=br0
      
        [Network]
        DHCP=ipv4
      		
    Configuring the physical layer.(Network Interface Configuration Files)
    In general you don't need a .link file since udev already identifies the device.
    However you can configure multiple options here that can't be set elsewhere. The most basic of these is the name.
    udev these days does a good job of consistently handling the naming of network devices.
    Wired interfaces are usually something like "enp5s0". This is derived from its PCI address:
    
      05:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 06)    
        
    enp5s0 isn't very descriptive if you've got multiple NICs in your system.
    To give the interface a more descriptive name. Simply create a .network file or a .link file to give it a more descriptive name.
    Configuration files for systemd-networkd (and systemd-resolved) can be placed in /usr/lib/systemd/network or /etc/systemd/network.
    Files in /etc/systemd/network have a higher priority than the ones in /usr/lib/systemd/network. There are three types of configuration files:
    • .link
    • Udev normally assigns network card interface names based on system physical characteristics such as enp2s1.
      If you prefer to use the classic or customized network interface names, there are three alternative ways to do that:
      • Mask udev's .link file for the default policy
      • 
        ln -s /dev/null /etc/systemd/network/99-default.link            
                    
      • Create a manual naming scheme
      • Network link configuration is performed by the net_setup_link udev builtin.
        The link files are read from the files located in:
        • /lib/systemd/network
        • the system network directory.
          /lib/systemd/network/99-default.link:
          
          [Match]
          OriginalName=*
          
          [Link]
          NamePolicy=keep kernel database onboard slot path
          AlternativeNamesPolicy=database onboard slot path
          MACAddressPolicy=persistent
          				
        • /run/systemd/network
        • the volatile runtime network directory
        • /etc/systemd/network
        • the local administration network directory.
          Files in /etc have the highest priority
        The link file contains 2 sections:
        • [Match]
        • determines if a given link file may be applied to a given device.
          A link file is said to match a device if each of the entries in the "[Match]" section matches.
          The following keys are accepted:
          • MACAddress=
          • The hardware address.
          • OriginalName=
          • A whitespace-separated list of shell-style globs matching the device name, as exposed by the udev property "INTERFACE".
            This cannot be used to match on names that have already been changed from userspace.
        • [Link]
        • specify how the device should be configured.
          The "[Link]" section accepts the following keys:
          • Name=
          • The interface name to use in case all the policies specified in NamePolicy= fail, or in case NamePolicy= is missing or disabled. Note that specifying a name that the kernel might use for another interface (for example "eth0") is dangerous because the name assignment done by udev will race with the assignment done by the kernel.
          • NamePolicy=
          • An ordered, space-separated list of policies by which the interface name should be set.
            Each of the policies may fail, and the first successful one is used. The name is not set directly, but is exported to udev as the property "ID_NET_NAME", which is, by default, used by a udev rule to set "NAME".
            The available policies are:
            • kernel
            • If the kernel claims that the name it has set for a device is predictable, then no renaming is performed.
          • Name=
          • The interface name to use in case all the policies specified in NamePolicy= fail, or in case NamePolicy= is missing or disabled.
        Create .link files in /etc/systemd/network/, that choose an explicit name or a better naming scheme for one, some, or all of your interfaces.
        For example:
        
        cat > /etc/systemd/network/10-ether0.link << "EOF"
        [Match]
        # Change the MAC address as appropriate for your network device
        MACAddress=12:34:45:78:90:AB
        
        [Link]
        Name=ether0
        EOF            
                    
      • Kernel boot parameter
      • 
                    
                    
    • .netdev
    • .network

Setting up cloud-init

cloud-init is used to configure the system during installation and first-boot.

Here are some examples of how to do common tasks with cloud-init.

create users with cloud-init

  • Create a file called meta-data
  • 
    instance-id: qeum-arm64
    local-hostname: qemu    
        
  • Create a file called user-data
  • 
    #cloud-config
    password: ubuntu
    chpasswd: {expire: False}
    ssh_pwauth: True
    ssh_authorized_keys:
      - ssh-rsa AAA...SDvZ user1@domain.com    
        
    The final line "ssh_authorized_keys:" above is an SSH public key.
    SSH public keys are found in ~/.ssh/id_rsa.pub.

Expire the cloud-user’s password so that the user must change it during their first login

  • user-data
  •     
    #cloud-config
    password: atomic
    chpasswd: {expire: True}
    ssh_pwauth: True
    ssh_authorized_keys:
      - ssh-rsa AAA...SDvz user1@yourdomain.com
      - ssh-rsa AAB...QTuo user2@yourdomain.com
        
    Note: This is a global setting.
    If you set expire to True all users who are created (see below) will have to change their password.

Change the default username

The default username is cloud-user.
Add the line user: to the user-data file:
  • user-data
  •     
    #cloud-config
    user: ubuntu
    password: ubuntu
    chpasswd: {expire: False}
    ssh_pwauth: True
    ssh_authorized_keys:
      - ssh-rsa AAA...SDvz user1@yourdomain.com
      - ssh-rsa AAB...QTuo user2@yourdomain.com    
        

Set the root password

To set the root password you must create a user list in the chpasswd section of the user-data file.
If you use this method to set the user passwords, all passwords must be set in this section. This means that the password: line must be moved from the top and into this section.
  • user-data
  •     
    #cloud-config
    ssh_pwauth: True
    ssh_authorized_keys:
      - ssh-rsa AAA...SDvz user1@yourdomain.com
      - ssh-rsa AAB...QTuo user2@yourdomain.com
    chpasswd:
      list: |
         root:ubuntu
         cloud-user:ubuntu
      expire: False 
        

Snappy Ubuntu Core and cloud-init

cloud-init is installed inside the Snappy image which allows you to customize the instance and automate its startup and configuration.
For example, at instance creation time you can specify a snappy application to be installed, cloud-init receives this information from the user in the form of ‘user-data’.
One of the formats that can be fed to cloud-init is called ‘cloud-config’.
cloud-config is yaml formatted data that is interpreted and acted on by cloud-init.
A couple specific configuration values have been aded in the snappy image:
  • ssh_enabled
  • Determine if ‘ssh’ service is started or not.
    By default ssh is not enabled.
  • packages
  • A list of snappy packages to install on first boot.
    Items in this list are snappy package names.

When running inside a snappy image, cloud-init still provides many of the features it provides on traditional instances:

  • runcmd
  • A list of commands run after boot has been completed.
    Commands are run as root.
    Each entry in the list can be a string or a list:
    • If the entry is a string, it is interpreted by ‘sh’.
    • If it is a list, it is executed as a command and arguments without shell interpretation.
  • ssh_authorized_keys
  • This is a list of strings.
    Each key present will be put into the default user’s ssh authorized keys file.
    Note that ssh authorized keys are also accepted via the cloud’s metadata service.
  • write_files
  • This allows you to write content to the filesystem.
    The module is still expected to work, but the user will have to be aware that much of the filesystem is read-only. Specifically, writing to file system locations that are not writable is expected to fail.

Example Cloud Config

Note that user data intended to be consumed as cloud-config must contain the first line ‘#cloud-config‘.

#cloud-config
snappy:
  ssh_enabled: True
  packages:
    – xkcd-webserver

write_files:
 – content: |
    #!/bin/sh
    echo “==== Hello Snappy!  It is now $(date -R) ====”
   permissions: ‘0755’
   path: /writable/greet

runcmd:
 – /writable/greet | tee /run/hello.log
The above user-data(because of #cloud-config) instructed cloud-init to do a number of different things:
  • instructed cloud-init to install the Snappy ‘xkcd-webserver’ application
  • it wrote a file via ‘write_files’ to a writable space on disk
  • executed that file with ‘runcmd

Use Ubuntu Server Cloud Image to Create a KVM Virtual Machine with Fixed Network Properties

To create a KVM VM using Ubuntu server 20.04 cloud image with the following network properties:
  • a static MAC address
  • a pre-defined network interface name
  • a static internal IP address

Preparation

  • Run the following command to install cloud image management utilities, cloud-image-utils:
  • 
    $ sudo apt install -y cloud-image-utils
    
  • Run the following command to install KVM and associate VM management packages:
  • 
    $ sudo apt install -y qemu-kvm libvirt-daemon-system bridge-utils virtinst
    
  • Add your local user to the kvm and libvirt groups:
  • 
    $ sudo usermod -aG kvm $USER
    $ sudo usermod -aG libvirt $USER
    
    Log out then log in again.
  • Download Ubuntu Server 20.04 Cloud Image:
  • 
    $ wget https://cloud-images.ubuntu.com/focal/current/focal-server-cloudimg-amd64.img
    
  • Create a disk image, vm01.qcow2, with 5 GB virtual size based on the Ubuntu server 20.04 cloud image:
  • 
    $ qemu-img create -F qcow2 -b focal-server-cloudimg-amd64.img -f qcow2 vm01.qcow2 5G
    $ ls -al
    total 537872
    drwxrwxr-x 2 jerry jerry      4096  二  13 18:02 .
    drwxrwxr-x 7 jerry jerry      4096  二   4 21:45 ..
    -rw-rw-r-- 1 jerry jerry 550567936  二   3 07:04 focal-server-cloudimg-amd64.img
    -rw-r--r-- 1 jerry jerry    196688  二  13 18:02 vm01.qcow2
    

Network Configuration

  • To generate a MAC address and write it to an environment variable, MAC_ADDR
  • For KVM VMs it is required that the first 3 pairs in the MAC address be the sequence 52:54:00.
    $RANDOM is an internal Bash function (not a constant) that returns a pseudorandom integer in the range 0 - 32767.
    
    $ export MAC_ADDR=$(printf '52:54:00:%02x:%02x:%02x' $((RANDOM%256)) $((RANDOM%256)) $((RANDOM%256)))
    $ echo $MAC_ADDR
    52:54:00:b0:c7:f1
    
  • Define the ethernet interface name and the internal IP address to be used in the KVM VM
  • 
    $ export INTERFACE=enp1s0
    $ export IP_ADDR=192.168.122.101
    
  • Create a network configuration file, network-config
  •   
    cat > network-config <<EOF
    ethernets:
        $INTERFACE:
            addresses: 
            - $IP_ADDR/24
            dhcp4: false
            gateway4: 192.168.122.1
            match:
                macaddress: $MAC_ADDR
            nameservers:
                addresses: 
                - 1.1.1.1
                - 8.8.8.8
            set-name: $INTERFACE
    version: 2
    EOF  
    

Cloud-Init Configuration

Basically, user-data is simply user-data and meta-data is a yaml formatted file representing.
  • Create meta-data:
  • 
      $ touch meta-data
      
  • Create user-data:
  • 
      $ cat > user-data <<EOF
    #cloud-config
    hostname: vm01
    manage_etc_hosts: true
    users:
      - name: vmadm
        sudo: ALL=(ALL) NOPASSWD:ALL
        groups: users, admin
        home: /home/vmadm
        shell: /bin/bash
        lock_passwd: false
    ssh_pwauth: true
    disable_root: false
    chpasswd:
      list: |
        vmadm:vmadm
      expire: false
    EOF
      
  • Create a disk image to attach with the network and cloud-init configuration
  • To use the data source NoCloud, you can provide meta-data and user-data to boot a local VM via files on a vfat or iso9660 filesystem.
    The filesystem volume label must be cidata or CIDATA. This is usually attached to the VM as a cdrom or transient 2nd vdisk
    cloud-localds creates a disk-image with user-data and/or meta-data for cloud-init. user-data can contain everything which is supported by cloud-init.
    
      $ cloud-localds -v --network-config=network-config seed.qcow2 user-data meta-data
    wrote seed.qcow2 with filesystem=iso9660 and diskformat=raw  
      
Information is consumed from the the root of the ‘cidata’ filesystem:
  • meta-data
  • the aggregate of /meta-data and /network-config
  • user-data
  • /user-data.

Provision a New Guest VM (NoCloud)

Creating Virtual machine can be done via virt-manager or virt-install command.
  • start the VM
  • virt-install is a command line tool for creating new KVM , Xen, or Linux container guests using the "libvirt" hypervisor management library.
    The guest can be configured to use one or more virtual disks, network interfaces, audio devices, physical USB or PCI devices, among others.
    Options:
    • --connect [hostname-or-URI]
    • The hypervisor connection URI specifies how to connect to the hypervisor.
      The most commonly used URIs are:
      • qemu:///system
      • connects locally as the root user to the daemon supervising guest virtual machines on the KVM hypervisor.
      • qemu:///session
      • connects locally as a user to the user's set of guest local machines using the KVM hypervisor.
      • lxc:///
      • connects to a local Linux container
    • --virt-type
    • The hypervisor to install on.
    • --name NAME
    • Name of the new guest virtual machine instance.
    • --memory OPTIONS
    • Memory to allocate for the guest, in MiB.
    • --vcpus OPTIONS
    • Number of virtual cpus to configure for the guest.
    • --import
    • Skip the OS installation process, and build a guest around an existing disk image.
      The device used for booting is the first device specified via "--disk" or "--filesystem".
    • --disk OPTIONS
    • Specifies media to use as storage for the guest.
      The general format of a disk string is
      
          --disk opt1=val1,opt2=val2,...
          	
      There are various options:
      • path
      • A path to some storage media to use, existing or not. Existing media can be a file or block device.
      • size
      • size (in GiB) to use if creating new storage
      • device
      • Disk device type.
        Example values are be 'cdrom', 'disk', 'lun' or 'floppy'.
        The default is 'disk'.
    • --network OPTIONS
    • Connect the guest to the host network.
      The value for "NETWORK" can take one of 4 formats:
      • network=NAME
      • Connect to a virtual network in the host called "NAME".
        Virtual networks can be listed, created, deleted using the "virsh" command line tool.
        In an unmodified install of "libvirt" there is usually a virtual network with a name of "default".
        Use a virtual network if the host has dynamic networking (eg NetworkManager), or using wireless. The guest will be NATed to the LAN by whichever connection is active.
      • bridge=BRIDGE
      • Connect to a bridge device in the host called "BRIDGE".
        Use this option if the host has static networking config and the guest requires full outbound and inbound connectivity to/from the LAN.
        Also use this if live migration will be used with this guest.
      • type=direct,source=IFACE[,source.mode=MODE]
      • Direct connect to host interface IFACE using macvtap.
      • user
      • none
      • Tell virt-install not to add any default network interface.
    • --noautoconsole
    • Don't automatically try to connect to the guest console.
      The default behaviour is to launch virt-viewer(1) to display the graphical console, or to run the "virsh console" command to display the text console.
    
    $ virt-install --connect qemu:///system 
                          --virt-type kvm 
                          --name vm01 
                          --ram 2048 
                          --vcpus=2 
                          --os-type linux 
                          --os-variant ubuntu20.04 
                          --disk path=/home/jerry/work/iso/vm01.qcow2,device=disk 
                          --disk path=/home/jerry/work/iso/seed.qcow2,device=disk 
                          --import 
                          --network network=default,model=virtio,mac=$MAC_ADDR 
                          --noautoconsol
    Starting install...
    Domain creation completed.
    
  • Check if the guest VM is running
  • 
    $ virsh list
     Id   Name   State
    ----------------------
     1    vm01   running
    
  • Login to the guest VM console
  • 
    $ virsh console vm01
    vm01 login: vmadm
    Password: 
    
  • connect to the guest VM using ssh
  • 
    $ ssh vmadm@192.168.122.101
    
  • Shutdown the guest KVM VM
  • 
    $ virsh destroy vm01
    $ virsh undefine vm01
    

Cloud Instance Initialization with cloud-init

An OS and its cloud must share some critical configuration data which tells the OS how to behave in its particular environment.
By separating configuration data, one can avoid the tight coupling of OS and cloud.
cloud-init provides a mechanism for separating out configuration data from the OS.

Introduction

cloud-init enables the automated provisioning of a basic OS image into a fully running state, complete with required access and applications.
Typical initialzation tasks handled by cloud-init:
  • networking
  • stoage
  • package installation
  • user account creation
  • security key provisioning for remote access
The following explains how a cloud instance is initialized from a disk image and the steps cloud-init takes on the image during boot.

Instance Initialization

An individual running system on a cloud is typically composed of:
  • disk image
  • The OS to be deployed. Many OS's have cloud-init pre-installed for cloud images.
  • metadata
  • Each cloud provider produces metadata which is used for setting up the instance.
    The source and format of the metadat varies from cloud to cloud.
    Some clouds use a drive attached to the instance, others use networking APIs.
    After deployment, the metadata can be queried :
    
    cloud-init query ds.meta_data
    {
     "dsmode": "net",
     "instance_id": "nocloud"
    }
      
  • user data(optional)
  • This is the interface for users to interact with cloud-init.
    This data can be a simple script file or a structured cloud-config file which uses cloud-init's built-in config modules.
  • vendor data(optional)

cloud-init

cloud-init Documentation

Cloud-init is the method for cloud instance initialization.
Cloud instances are initialized from a disk image with instance data:
  • Cloud metadata
  • User data (optional)
  • Vendor data (optional)

Cloud-init will identify the cloud which the cloud instance is running on during boot, read any provided metadata from the cloud and initialize the system accordingly.

This may involve : setting up the network and storage devices to configuring SSH access key and many other aspects of a system.

Boot Stages

In order to be able to provide the functionality that it does, cloud-init must be integrated into the boot in fairly controlled way.
There are five stages :
  • Generator
  • When booting under systemd, a generator will run that determines if cloud-init.target should be included in the boot goals.
    It will not enable cloud-init if either:
    • The file /etc/cloud/cloud-init.disabled exists
    • The kernel command line as found in /proc/cmdline contains cloud-init=disabled.
    • When running in a container, the kernel command line is not honored, but cloud-init will read an environment variable named KERNEL_CMDLINE in its place.
      These mechanisms for disabling cloud-init at runtime currently only exist in systemd.
  • Local
  • The systemd service cloud-init-local.service runs as soon as possible with / mounted read-write.
    In most cases, this stage does :
    • locate “local” data sources
    • apply networking configuration to the system (including “Fallback”)
    It finds the datasource and determines the network configuration to be used. That network configuration can come from:
    • datasource
    • cloud provided network configuration via metadata
    • fallback
    • cloud-init’s fallback networking consists of rendering the equivalent to “dhcp on eth0”, which was historically the most popular mechanism for network configuration of a guest
    • none
    • network configuration can be disabled by writing the file /etc/cloud/cloud.cfg with the content: network: {config: disabled}
    If this is an instance’s first boot, then the selected network configuration is rendered. This includes clearing of all previous (stale) configuration including persistent device naming with old mac addresses.
    Cloud-init then exits and expects for the continued boot of the operating system to bring network up as configured settings.
  • Network
  • The systemd service, cloud-init.service runs after local stage and configured networking is up.
    This stage requires all configured networking to be online, as it will fully process any user-data that is found.
  • Config
  • The systemd service cloud-config.service runs after network.
  • Final
  • The systemd service cloud-final.service as final part of boot (traditional “rc.local”).

First Boot Determination

cloud-init has to determine whether or not the current boot is the first boot of a new instance or not, so that it applies the appropriate configuration.
  • On an instance’s first boot, it should run all “per-instance” configuration
  • On a subsequent boot it should run only “per-boot” configuration.
When it runs, cloud-init stores a cache of its internal state for use across stages and boots.
By checking the instance ID in the cache against the instance ID it determines at runtime, cloud-init determines which case it is running.
Internally, cloud-init refers to this behavior as check. cloud-init exposes the manual_cache_clean configuration option:
  • false (the default)
  • cloud-init will check and clean the cache if the instance IDs do not match
  • true
  • cloud-init will trust the existing cache (and therefore not clean it).

CLI Interface


$ cloud-init --help
An overview of each of the subcommands
  • analyze
  • Analyze cloud-init logs and data.
    Possible subcommands include:
    • blame
    • report ordered by most costly operations
    • dump
    • machine-readable JSON dump of all cloud-init tracked events
    • show
    • show time-ordered report of the cost of operations during each boot stage
    • boot
    • show timestamps from kernel initialization, kernel finish initialization, and cloud-init start
  • clean
  • Remove cloud-init artifacts from /var/lib/cloud to simulate a clean instance.
  • collect-logs
  • Collect and tar cloud-init generated logs, data files, and system information for triage.
  • devel
  • features
  • init
  • modules
  • query
  • single
  • status

FAQ

Where are the logs?

  • /var/log/cloud-init-output.log
  • captures the output from each stage of cloud-init when it runs
  • /var/log/cloud-init.log
  • very detailed log with debugging output, detailing each action taken
  • /run/cloud-init
  • contains logs about how cloud-init decided to enable or disable itself, as well as what platforms/datasources were detected. These logs are most useful when trying to determine what cloud-init ran or did not run.

Where are the configuration files?

These files can define the modules that run during instance initialization, the datasources to evaluate on boot, and other settings.
  • /etc/cloud/cloud.cfg
  • /etc/cloud/cloud.cfg.d/*.cfg

Where are the data files?

  • /var/lib/cloud/instance/
  • This is a symbolic link that points to the most recenlty used instance-id directory. This folder contains the information cloud-init received from datasources, including vendor and user data.
  • /var/lib/cloud/data/
  • This directory contain information related to the previous boot

What datasource am I using?

To find what datasource is getting used

$ cloud-id
If the cloud-id is not what is expected, run the scrip to debug it:

$ sudo DEBUG_LEVEL=2 DI_LOG=stderr /usr/lib/cloud-init/ds-identify --force

Debug


$ sudo DI_LOG=stderr /usr/lib/cloud-init/ds-identify --force
$ sudo cloud-init clean --logs
$ sudo cloud-init init --local
$ sudo cloud-init init
These commands will re-run cloud-init as if this were first boot of a system.

Two of the most common issues with user data, that also happens to be cloud-config is:

  • Incorrectly formatted YAML
  • First line does not contain #cloud-config

User-Data Formats

Cloud config examples

Modules

Merging User-Data Sections

Instance

Datasources

Vendor Data

Network Configuration

Default Behavior

Cloud-init searches for network configuration in order of increasing precedence; each item overriding the previous:
  • Datasource
  • For example, OpenStack may provide network config in the MetaData Service
  • System Config
  • All files with the '.cfg' extension in /etc/cloud/cloud.cfg.d/* will be read by cloud-init.
  • Kernel Command Line
  • One of the following 2 ways:
    • ip=
    • network-config=<Base64 encoded YAML config string>
In the absence of network configuration in any of the above sources , cloud-init will write out a network configuration that will issue a DHCP request on a “first” network interface.

Disabling Network Configuration

Users may disable Cloud-init ‘s network configuration capability and rely on other methods, such as embedded configuration or other customizations.
Cloud-init supports the following methods for disabling cloud-init‘s network configuration capability :
  • Kernel Command Line
  • 
      	network-config=disabled
        
  • cloud config
  • In the combined cloud-init configuration dictionary ( merged from /etc/cloud/cloud.cfg and /etc/cloud/cloud.cfg.d/* ) :
    
    network:
      config: disabled  
      
If Cloud-init ‘s networking config has not been disabled, and no other network information is found, then it will proceed to generate a fallback networking configuration.

Fallback Network Configuration

Cloud-init will attempt to determine which of any attached network devices is most likely to have a connection and then generate a network configuration to issue a DHCP request on that interface.
After selecting the “right” interface, a configuration is generated and applied to the system.

Network Configuration Sources

Cloud-init accepts a number of different network configuration formats in support of different cloud substrates.
  • Config Drive
  • Digital Ocean
  • OpenNebula
  • OpenStack
  • SmartOS Datasource
  • UpCloud
  • NoCloud
  • The data source NoCloud allows the user to provide user-data and meta-data to the instance without having a network at all.
    This can be provided by 2 ways:
    • provide meta-data and user-data to a local VM boot via files on a vfat or iso9660 filesystem
    • The filesystem volume label must be cidata or CIDATA.
    • provide meta-data via kernel command line
    • The parameter must be passed in one of the following forms:
      • ds=nocloud[;key=val;key=val]
      • ds=nocloud-net[;key=val;key=val]
      The permitted keys are:
      • h or local-hostname
      • i or instance-id
      • s or seedfrom
        • With ds=nocloud, the seedfrom value must start with / or file://
        • With ds=nocloud-net, the seedfrom value must start with http:// or https://.
Cloud-init delegates rendering of the configuration to Distro supported formats.
The following renderers (configurations) are supported in cloud-init with the order of preference:
  • ENI
  • /etc/network/interfaces or ENI is supported by the ifupdown package
  • Sysconfig
  • Sysconfig format is used by RHEL, CentOS, Fedora and other derivatives.
  • Netplan
  • netplan consumes Networking Config Version 2 input and renders network configuration for supported backends such as systemd-networkd and NetworkManager.
Users may override the network renderer policy by supplying an updated configuration in /etc/cloud/cloud.config:

system_info:
  network:
    renderers: ['netplan', 'eni', 'sysconfig']

KVM: Testing cloud-init locally using KVM for an Ubuntu cloud image

Prerequisites

Install the tool managing cloud-images

$ sudo apt install -y cloud-image-utils
Download the Ubuntu cloud image

$ wget https://cloud-images.ubuntu.com/focal/current/focal-server-cloudimg-amd64.img

Create cloud-init configuration

Create a file named “cloud_init.cfg”: (refer to Modules)

#cloud-config
hostname: test1
fqdn: test1.example.com
manage_etc_hosts: true
users:
  - name: ubuntu
    sudo: ALL=(ALL) NOPASSWD:ALL
    groups: users, admin
    home: /home/ubuntu
    shell: /bin/bash
    lock_passwd: false
    ssh-authorized-keys:
      - <sshPUBKEY>
# only cert auth via ssh (console access can still login)
ssh_pwauth: false
disable_root: false
chpasswd:
  list: |
     ubuntu:linux
  expire: False
packages:
  - qemu-guest-agent
# written to /var/log/cloud-init-output.log
final_message: "The system is finally up, after $UPTIME seconds"
Then replace the “<sshPUBKEY>” placeholder in the file above, with the content of “id_rsa.pub”.

Create network configuration

Create a file named “network_config_static.cfg” to define the networking parameters.

version: 2
ethernets:
  ens3:
     dhcp4: false
     # default libvirt network
     addresses: [ 192.168.122.158/24 ]
     gateway4: 192.168.122.1
     nameservers:
       addresses: [ 192.168.122.1,8.8.8.8 ]
       search: [ example.com ]

Insert metadata into seed image


# insert network and cloud config into seed image
cloud-localds -v --network-config=network_config_static.cfg test1-seed.img cloud_init.cfg

# show seed disk just generated
$ qemu-img info test1-seed.img
cloud-localds:

Usage: cloud-localds [ options ] output user-data [meta-data]

   Create a disk for cloud-init to utilize nocloud

   options:
     -h | --help             show usage
     -d | --disk-format D    disk format to output. default: raw
                             can be anything supported by qemu-img or
                             tar, tar-seed-local, tar-seed-net
     -H | --hostname    H    set hostname in metadata to H
     -f | --filesystem  F    filesystem format (vfat or iso), default: iso9660

     -i | --interfaces  F    write network interfaces file into metadata
     -N | --network-config F write network config file to local datasource
     -m | --dsmode      M    add 'dsmode' ('local' or 'net') to the metadata
                             default in cloud-init is 'net', meaning network is
                             required.
     -V | --vendor-data F    vendor-data file
     -v | --verbose          increase verbosity

   Note, --dsmode, --hostname, and --interfaces are incompatible
   with metadata.

   Example:
    * cat my-user-data
      #cloud-config
      password: passw0rd
      chpasswd: { expire: False }
      ssh_pwauth: True
    * echo "instance-id: $(uuidgen || echo i-abcdefg)" > my-meta-data
    * cloud-localds my-seed.img my-user-data my-meta-data
    * kvm -net nic -net user,hostfwd=tcp::2222-:22 \
         -drive file=disk1.img,if=virtio -drive file=my-seed.img,if=virtio
    * ssh -p 2222 ubuntu@localhost

Start VM


virt-install --name test1 \
  --virt-type kvm --memory 2048 --vcpus 2 \
  --boot hd,menu=on \
  --disk path=test1-seed.img,device=cdrom \
  --disk path=snapshot-bionic-server-cloudimg.qcow2,device=disk \
  --graphics vnc \
  --os-type Linux --os-variant ubuntu18.04 \
  --network network:default \
  --console pty,target_type=serial
After the machine has booted up and you have given cloud-init a couple of minutes to configure networking, you should be able to login to this guest OS from either virt-viewer or ssh.

ssh ubuntu@192.168.122.158 -i id_rsa

# final cloud-init status
cat /run/cloud-init/result.json

# cloud logs
vi /var/log/cloud-init.log
vi /var/log/cloud-init-output.log

netplan

Netplan configuration examples

Configuration

To configure netplan, save configuration files under /etc/netplan/ with a .yaml extension (e.g. /etc/netplan/config.yaml), then run sudo netplan apply. This command parses and applies the configuration to the system.

Configuration written to disk under /etc/netplan/ will persist between reboots.

Network - Configuration

Ethernet Interface Logical Names

As boot processes became less linear and interfaces became more hotpluggable this became more of a concern.
For ex., eth0 and eth1 might switch places on successive boots.

The classic naming scheme for network interfaces applied by the kernel is to simply assign names beginning with "eth0", "eth1", ... to all interfaces as they are probed by the drivers.
But these names do not necessarily correspond to actual labels on the chassis.

In recent Linux distribution, systemd/udev will automatically assign predictable, stable network interface names for all local Ethernet, WLAN and WWAN interfaces.
The default is to assign fixed names based on firmware, topology, and location information.

Assigning fixed names based on firmware/topology/location information has the big advantage that the names are fully automatic, fully predictable, that they stay fixed even if hardware is added or removed.
With systemd (v 197), the following different naming schemes for network interfaces are now supported by udev natively:

  • Firmware or BIOS provided index numbers for on-board devices
  • example: eno1
  • Firmware or BIOS provided PCI Express hotplug slot index numbers
  • example: ens1
  • physical/geographical location information of the connector of the hardware
  • example: enp2s0
  • interface's MAC address
  • example: enx78e7d1ea46da
  • unpredictable kernel naming scheme
  • if all other methods fail (example: enp1s0)
This combined policy is only applied as last resort.
That means,
  • if the system has biosdevname installed, it will take precedence.
  • This requires passing biosdevname=1 as a kernel command-line parameter.
  • if the user has added udev rules which change the name of the kernel devices these will take precedence
  • any distribution specific naming schemes generally take precedence.

HowTo Change Network Interface Name in Linux Permanently:

  • Find the the ports you wish to change their names
  • Collect the device information for matching.
    
        	$ ifconfig
            
  • Create the udev rule
  • /etc/udev/rules.d/70-persistent-net.rules.
    Add the following line per device.
    
            	SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="7c:fe:90:cb:76:02", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth1"
            

Interface logical names can also be configured via a netplan configuration.
If you would like control which interface receives a particular logical name use the match and set-name keys.


network:
  version: 2
  renderer: networkd
  ethernets:
    eth_lan0:
      dhcp4: true
      match:
        macaddress: 00:11:22:33:44:55
      set-name: eth_lan0
  • The match key is used to find an adapter based on some criteria like MAC address, driver, etc.
  • Then the set-name key can be used to change the device to the desired logial name.

Ethernet Interface Settings

Aapplication that can help identify all network interfaces available to your system:
  • lshw
  • lshw is a small tool to extract detailed information on the hardware configuration of the machine.
    It currently supports DMI (x86 and IA-64 only), OpenFirmware device tree (PowerPC only), PCI/AGP, CPUID (x86), IDE/ATA/ATAPI, PCMCIA (only tested on x86), SCSI and USB.
    	
    $ sudo lshw -class network
      	
  • ethtool
  • Query or control network driver and hardware settings s such as auto-negotiation, port speed, duplex mode, and Wake-on-LAN. .
    	
    $ sudo ethtool enp3s0
      	

IP settings

  • configure an IP address
  • 
    $ sudo ip addr add 10.102.66.200/24 dev enp0s25        
            
  • configure interface up/dpwn
  • 
    $ sudo ip link set dev enp0s25 up
    $ sudo ip link set dev enp0s25 down        
            
  • configure a default gateway
  • 
    $ sudo ip route add default via 10.102.66.1        
            

在 QEMU 使用 Ubuntu Cloud Images

Cloud Image 是已經預先裝好作業系統的磁碟映像.

一些 Cloud Image 像是 Ubuntu Cloud Image 會在初始化時執行 cloud-init。
The Ubuntu cloud images are pre-installed images that allow your to boot directly without doing the usual desktop system installation.

  • 下載 Ubuntu Cloud Images
  • focal-server-cloudimg-amd64.img

  • 製作供 cloud-init 使用的映像檔
  • 用data source NoCloud 來設定 cloud-init,需要一個 ISO 檔,它的 volume label(掛載之後顯示的名稱)要是 cidataCIDATA,裡面要包含 2 個檔案:
    • meta-data
    • user-data
    我們可以用 cloud-localds 指令製作出符合格式的映像檔:
    • 安裝 cloud-utils
    • cloud-localds 指令包含在 cloud-utils 套件中.
      
                  	sudo apt install cloud-image-utils
                  
    • 新增一個檔案記錄cloud-init將使用的設定
    • 更多設定,可以看文件。 只要設定密碼, user-data.txt:
      
      #cloud-config
      password: 你的密碼
      chpasswd: { expire: False }
      ssh_pwauth: True
      			
      登入帳號是 ubuntu,密碼是你設定的密碼。
    • 使用 cloud-localds做映像檔seed.iso
    •           	
      cloud-localds seed.iso user-data.txt
      			
      cloud-localds 在製作映像檔時可以自己產生預設的 meta-data 檔,所以不用提供。
                
      {
      "instance-id": "iid-local01"
      }          
      			
    • 自己做映像檔seed.iso
    • 自己提供這個meta-data 檔案:
                	
      genisoimage  -output seed.iso -volid cidata -joliet -rock user-data meta-data
      			
  • 啓動磁碟映像
    • Back up the original images
    • 
      $ cp ~/work/imgs/focal-server-cloudimg-amd64.img .
        		
    • Resize the image
    • 
      $ ls -l focal-server-cloudimg-amd64.img   
      -rw-rw-r-- 1 jerry jerry 552468480 Feb 22 08:29 focal-server-cloudimg-amd64.img
      $ qemu-img resize focal-server-cloudimg-amd64.img 8G
      		
    • Start the image
      • Use virt-install
      • 
        virt-install \
          --name ubuntu20.04 \
          --memory 512 \
          --disk focal-server-cloudimg-amd64.img,device=disk,bus=virtio \
          --disk seed.iso,device=cdrom \
          --os-type linux \
          --os-variant ubuntu20.04 \
          --virt-type kvm \
          --graphics none \
          --network network=default,model=virtio \
          --import
          			
      • Use virt-manager
        • "New Virtual Machine"
        • "Import existing disk image"
        • "Provide the existing storage path" to the image
        • "Choose Memory and CPU settings"
        • "Ready to begin the installation"
        • Click "Customize configuration before install" and "Finish":
          • Click "Add Hardware"
          • Finish
        • click "Begin Installation"

Introduction to AppArmor

Using NetworkManager and ModemManager in Linux to automatically establish and maintain a connection

This will show how to set up NetworkManager to automatically configure, establish and maintain the cellular data connection in your system.

NetworkManager and ModemManager are open source tool for Linux to manage several types of networks and interfaces such as ethernet, wifi, etc. It can also manage cellular WWAN interfaces through the ModemManager tool.

It is hosted by the Freedesktop.org community and driven by Aleksander Morgado and other contributors. please visit https://wiki.gnome.org/Projects/NetworkManager and https://www.freedesktop.org/wiki/Software/ModemManager/ for latest information.

ModemManager is capable of communicating over several types of device control channels such as QMI/RMNET, MBIM, MODEM / AT command etc.

Installation


$ apt install network-manager
$ NetworkManager -V
$ ModemManager -V
Both NetworkManager and ModemManager have command line interfaces (nmcli and mmcli respectively) where you can interact with the management tools.

Have ModemManager list all the cellular device it has detected:


$  mmcli --list-modems
  
General details and status of the modem can be listed with:

$  mmcli --modem=0
  
Check if the cellular device is managed by NetworkManager :

$ nmcli device status
  
Now you should create a connection profile in NetworkManager for your specific network carrier and SIM card with the "nmcli connection add" command:


  

留言

熱門文章