This is yet another short blog post and this time it is about how to automatically update the primary IP for cPanel using a basic CLI script.

The following script can be used by pasting in the content using an editor of your choice and then executing it:

#!/bin/bash
# cPanel IP Updater script, by blog.prime.re
# This script automatically handles the changing of primary IP for cPanel instances
set -e
SYSTEM_PRIMARY_IP=$(curl -s icanhazip.com)
if [[ ${SYSTEM_PRIMARY_IP} =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  echo "Valid IP found! The following primary IP will be used: ${SYSTEM_PRIMARY_IP}"
else
  echo "Error: The system IP could not be queried and validated using icanhazip." && exit 0
fi

read -p "This script will update cPanel IP to ${SYSTEM_PRIMARY_IP}. Are you sure you want to do this? y/n " -n 1 -r
printf "\n\n"
if [[ $REPLY =~ ^[Yy]$ ]] ; then
  echo ${SYSTEM_PRIMARY_IP} > /var/cpanel/mainip
  sed -i "/ADDR/c\ADDR ${SYSTEM_PRIMARY_IP}" /etc/wwwacct.conf
  /scripts/mainipcheck
  /usr/local/cpanel/cpkeyclt --force
else
  echo "Error: Script was aborted by the user" && exit 1
fi

Or you can download the script directly here.

It will make all the necessary changes and update the cPanel configuration to the primary IP of the server and then run the necessary scripts to make the change persistent.