kvm/bolt_vm_automation/tasks/system_setup.sh

64 lines
2.0 KiB
Bash

#!/bin/bash
# Using Bolt's environment variables
IP="${PT_ip_with_cidr}"
HOSTNAME="${PT_hostname}"
DHCP="${PT_dhcp}"
GATEWAY="${PT_gateway}"
NAMESERVER1="${PT_nameserver1}"
NAMESERVER2="${PT_nameserver2}"
NAMESERVER3="${PT_nameserver3}"
# Check if all required parameters are provided
if [ -z "$IP" ] || [ -z "$HOSTNAME" ] || [ -z "$DHCP" ] || [ -z "$GATEWAY" ] || [ -z "$NAMESERVER1" ] || [ -z "$NAMESERVER2" ] || [ -z "$NAMESERVER3" ]; then
echo "Missing required parameters. All parameters must be provided."
exit 1
fi
# Configure and install iptables-persistent
sudo DEBIAN_FRONTEND=noninteractive apt-get -y install iptables-persistent
# Restrict SSH access
sudo iptables -A INPUT -p tcp --dport 22 -s 100.40.223.128/26 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 22 -s 173.62.109.73/32 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 22 -j DROP
# Use netfilter-persistent to save rules instead of direct file writing
sudo netfilter-persistent save
# Create the new netplan configuration
sudo tee /etc/cloud/cloud.cfg.d/90-installer-network.cfg << EOL
network:
version: 2
ethernets:
enp1s0:
dhcp4: ${DHCP}
EOL
# If DHCP is false, add static IP configuration
if [ "$DHCP" = "false" ]; then
sudo tee -a /etc/cloud/cloud.cfg.d/90-installer-network.cfg << EOL
addresses:
- ${IP}
routes:
- to: default
via: ${GATEWAY}
nameservers:
addresses: [${NAMESERVER1}, ${NAMESERVER2}, ${NAMESERVER3}]
EOL
fi
# Set the hostname
sudo hostnamectl set-hostname "${HOSTNAME}"
echo "${HOSTNAME}" | sudo tee /etc/hostname > /dev/null
# Update /etc/hosts
sudo sed -i "s/127.0.1.1.*/127.0.1.1\t${HOSTNAME}/" /etc/hosts
echo "System configuration completed successfully"
# Apply network configuration in the background and exit before it takes effect
# nohup bash -c "(sleep 2 && sudo netplan apply) &" > /dev/null 2>&1
# exit 0
nohup bash -c "(sleep 2 && sudo reboot) &" > /dev/null 2>&1
exit 0