Skip to content

Instantly share code, notes, and snippets.

@VahagnMian
Created April 6, 2024 20:59
Show Gist options
  • Save VahagnMian/3c0fc839e0767426ec9ef755a8b848a4 to your computer and use it in GitHub Desktop.
Save VahagnMian/3c0fc839e0767426ec9ef755a8b848a4 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Backup the Microk8s directory
mkdir -p /var/snap/backup/microk8s-current
cp -r /var/snap/microk8s/current/ /var/snap/backup/microk8s-current
if [ $? != 0 ]; then
echo "[ ERROR ] happened during backing up microk8s directory "
exit 1
else
echo "[ OK ] Successfully backed up microk8s directory"
fi
# Define the file path
FILE="/var/snap/microk8s/current/args/kube-apiserver"
# Define the lines to be added
LINE1="--kubelet-certificate-authority=\${SNAP_DATA}/certs/ca.crt"
LINE2="--kubelet-preferred-address-types=InternalIP,Hostname,InternalDNS,ExternalDNS,ExternalIP"
# Check if the file contains any of the lines
if grep -q -- "${LINE1}" "${FILE}" || grep -q -- "${LINE2}" "${FILE}"; then
echo "[ WARN ] The kube-apiserver file already contains one of the specified lines."
exit 1
else
# If the lines are not found, append them to the file
echo "${LINE1}" >> "${FILE}"
echo "${LINE2}" >> "${FILE}"
echo "[ OK ] Successfuly Added lines for kubelet certificate authority"
fi
# Generate SSL certificate
BASE_PATH=/var/snap/microk8s/current/certs
rm -r ${BASE_PATH}/kubelet.*
if [ $? != 0 ]; then
echo "[ ERROR ] happened during removing of old kubelet keys and certs"
exit 1
else
echo "[ OK ] Successfully deleted old kubelet certs"
fi
openssl genrsa -out ${BASE_PATH}/kubelet.key 2048 >/dev/null 2>&1
if [ $? != 0 ]; then
echo "[ ERROR ] happened during generation of kubelet private key "
exit 1
else
echo "[ OK ] Successfully generated private key"
fi
# Generate CSR from private key
openssl req -new -key ${BASE_PATH}/kubelet.key -out ${BASE_PATH}/kubelet.csr -config ${BASE_PATH}/csr.conf >/dev/null 2>&1
if [ $? != 0 ]; then
echo "[ ERROR ] happened during generation of CSR "
exit 1
else
echo "[ OK ] Successfully generated CSR"
fi
# Generating new kubelet certs using CA and CSR
openssl x509 -req -in ${BASE_PATH}/kubelet.csr -CA ${BASE_PATH}/ca.crt -CAkey ${BASE_PATH}/ca.key -CAcreateserial -out ${BASE_PATH}/kubelet.crt -days 365 -extensions req_ext -extfile ${BASE_PATH}/csr.conf -sha256 >/dev/null 2>&1
if [ $? != 0 ]; then
echo "[ ERROR ] happened during generation of kubelet certs "
exit 1
else
echo "[ OK ] Successfully generated kubelet certs"
fi
snap restart microk8s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment