Saturday, November 7, 2020

Set static IP address in ubuntu 18.04

Starting from ubuntu 18.04, network configuration is now handled by netplan, which is based on YAML.


To set a static ip in netplan, you need to know what is the interface name that you want to configure. To do that, just run "ip address" command
$ ip address
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: enp0s3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 08:00:27:18:46:ea brd ff:ff:ff:ff:ff:ff
    inet 192.168.0.154/24 brd 192.168.0.255 scope global dynamic enp0s3
       valid_lft 604595sec preferred_lft 604595sec
    inet6 2001:e68:542c:e410:a00:27ff:fe18:46ea/64 scope global dynamic mngtmpaddr noprefixroute 
       valid_lft 259188sec preferred_lft 172788sec
    inet6 fe80::a00:27ff:fe18:46ea/64 scope link 
       valid_lft forever preferred_lft forever
3: enp0s8: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN group default qlen 1000
    link/ether 08:00:27:7d:fa:68 brd ff:ff:ff:ff:ff:ff

You can see that we have 2 interfaces, enp0s3 and enp0s8. Now we have to locate which file need to be edited to give enp0s8 a static IP address. We can do that by:
$ ls /etc/netplan/
01-netcfg.yaml

To add an ip address  of 10.10.10.10/24 to enp0s8, with gateway 10.10.10.1 and nameserver 8.8.8.8 and 8.8.4.4, simply edit /etc/netplan/01-netcfg.yaml as per below
$ sudo vi /etc/netplan/01-netcfg.yaml
network:
  version: 2
  renderer: networkd
  ethernets:
    enp0s3:
      dhcp4: yes
    enp0s8
      dhcp4: no
      addresses: [10.10.10.10/24]
      gateway4: 10.10.10.1
      nameservers:
        addresses: [8.8.8.8,8.8.4.4]

Save the file. Since this is a yaml based configuration, make sure that the indentation is uniform across the file. To test your configuration for any syntax error, and press ENTER if you agree to use the configuration:
$ sudo netplan try
Do you want to keep these settings?


Press ENTER before the timeout to accept the new configuration


Changes will revert in 119 seconds
Configuration accepted.  

Once accepted, verify the ip has been set using "ip address" and "ip route"
$ ip address show dev enp0s8
3: enp0s8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 08:00:27:7d:fa:68 brd ff:ff:ff:ff:ff:ff
    inet 10.10.10.10/24 brd 10.10.10.255 scope global enp0s8
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fe7d:fa68/64 scope link 
       valid_lft forever preferred_lft forever

$ ip route show dev enp0s8
default via 10.10.10.1 proto static 
10.10.10.0/24 proto kernel scope link src 10.10.10.10 

No comments: