Skip to content

Instantly share code, notes, and snippets.

@norandom
Last active February 15, 2024 17:40
Show Gist options
  • Save norandom/91ab977399a35e2fdb405ae0da165607 to your computer and use it in GitHub Desktop.
Save norandom/91ab977399a35e2fdb405ae0da165607 to your computer and use it in GitHub Desktop.
Persist DHCP provisioned IP config (Debian, Ubuntu, netplan)
#!/bin/bash
# Interface name
IFACE="enp1s0"
# Get current IP, netmask, and gateway
IP=$(ip addr show $IFACE | grep 'inet ' | awk '{print $2}')
GATEWAY=$(ip route | grep default | awk '{print $3}')
DNS=$(awk '/^nameserver/ {print $2}' /run/systemd/resolve/resolv.conf | tr '\n' ' ')
# Backup current Netplan configuration
cp /etc/netplan/01-netcfg.yaml /etc/netplan/01-netcfg.yaml.backup
# Write new config to the Netplan configuration file
cat <<EOT > /etc/netplan/01-netcfg.yaml
network:
version: 2
renderer: networkd
ethernets:
$IFACE:
dhcp4: no
addresses: [$IP]
routes:
- to: default
via: $GATEWAY
nameservers:
addresses: [$DNS]
EOT
# Apply the Netplan configuration
netplan apply
echo "Static IP configuration for $IFACE, including DNS, is complete."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment