Make a copy of your /etc/netplan/50-cloud-init.yaml
at any location you choose - here referenced as /path/to/50-cloud-init.yaml
(at the same time this file serves as a backup).
The content of this file should be along the lines of:
version: 2
wifis:
renderer: networkd
wlan0:
dhcp4: true
optional: true
access-points:
SSID:
password: PASS
The important thing here is that the SSID
and PASS
are given as stated here. Adjust the contents to match your specific network config.
Then make a text file for your bash script, also anywhere you like and make it executable - here referenced as /path/to/bash-script
.
The content of this file should then be:
#!/bin/bash
# check if script is run as root
if [[ "$EUID" -ne 0 ]]; then
echo "Please run this script as root / with sudo."
exit 1
fi
# assign values to $SSID and $PASS variables - you can add additional SSID and password pairs if you like.
case "$1" in
<SSID1>)
SSID=<SSID1>
PASS=<PASS1>
;;
<SSID2>)
SSID=<SSID2>
PASS=<PASS2>
;;
esac
# only do something if $SSID variable has been set
if [[ -n "$SSID" ]]; then
# copy your template file into the netplan folder
cp -f /path/to/50-cloud-init.yaml /etc/netplan/50-cloud-init.yaml
# replace the "variables" in the netplan config file with the actual values
sed -i "s/SSID/$SSID/;s/PASS/$PASS/" /etc/netplan/50-cloud-init.yaml
# apply netplan config
netplan apply
# restart networkd
systemctl restart systemd-networkd
else
echo "Invalid SSID given".
exit 1
fi
Replace all instances of <SSIDx>
and <PASSx>
with your actual SSID and passwords.
Now run your script /path/to/bash-script
with your chosen SSID
as the first parameter, like:
/path/to/bash-script <SSIDx>
And this will do what you're after.