Attach a network to a VM
Attaches a virtual network (VLAN) to a Virtual Machine. Work runs asynchronously and returns 202 Accepted. A running VM restarts so the new NIC reaches the guest; a VM that is not running picks it up when it next starts.
After the restart, check the interface inside the guest (ip -br addr):
- VMs created with
apply_network_on_bootenabled (the default) configure the NIC on boot, with the attachment’saddresswhen one was given. Nothing else to do. - VMs created before that option existed, or with it disabled, leave the NIC without an address. Once the VM has restarted, read the attachment’s
mac_addressandaddressfromGET /virtual_machines/{virtual_machine_id}/network_attachmentsand configure the interface with that MAC address yourself, as described in Private networks: configure the OS. The NIC gets a new MAC address each time a network is attached, so update your configuration after detaching and attaching a network again.
Keep network configuration of your own in a separate file. With apply_network_on_boot, every boot, including a restart started inside the guest, rewrites cloud-init’s own network file (for example /etc/netplan/50-cloud-init.yaml), so changes made there are lost. To stop that on a VM, create /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg containing network: {config: disabled}; cloud-init then leaves the network configuration alone on every boot, and networks attached afterwards must be configured by hand.
Some virtual machines run on older infrastructure that doesn’t support network attachments. On those VMs, attaching or detaching a network returns 422 VIRTUAL_NETWORK_ATTACHMENT_UNSUPPORTED and leaves the VM unchanged.