A.3 node_exporter.sh

#!/bin/bash

# Checking for prometheus user
USERID="$1"

if grep -q "^prometheus:" /etc/passwd; then
   echo "User $USERID exists in /etc/passwd"
else
   echo "User $USERID does not exist in /etc/passwd"
   sudo useradd --no-create-home --shell /bin/false prometheus
   echo "User $USERID created"
fi

# Checking for prometheus group
if grep -q "^prometheus:" /etc/group; then
   echo "Group $USERID exists in /etc/group"
else
   echo "Group $USERID does not exist in /etc/group"
   sudo groupadd prometheus
   echo "Group $USERID created"
fi

# Creating the node_exporter directory to keep binary files
DIR="/etc/nodeexporter"

if [[ -d "$DIR" ]]; then
  echo "Directory already exists: $DIR"
else
  sudo mkdir "$DIR"
  echo "Directory created: $DIR"
fi

# Copying binary to /etc/nodeexporter
if sudo cp node_exporter "$DIR"; then
   echo "Copy of node exporter binary successful"
else
   echo "Copy of node exporter binary unsuccessful"
fi

# Creating node_exporter service file
SERVICE_FILE="/etc/systemd/system/node_exporter.service"

sudo tee "$SERVICE_FILE" > /dev/null <<EOF
[Unit]
Description=node_exporter
Wants=network-online.target
After=network-online.target

[Service]
User=prometheus
Group=prometheus
Type=simple
ExecStart=/etc/nodeexporter/node_exporter

[Install]
WantedBy=multi-user.target
EOF

echo "node_exporter service file created: $SERVICE_FILE"

# Adding prometheus port to firewall
if grep -q "VERSION = 2023" /etc/novell-release; then
   DEFAULT_ZONE=$(firewall-cmd --get-default-zone)
   for port in 9100; do
      sudo firewall-cmd --permanent --zone="$DEFAULT_ZONE" --add-port="${port}/tcp" > /dev/null
   done
   sudo firewall-cmd --add-masquerade --permanent --zone="$DEFAULT_ZONE" > /dev/null
   sudo firewall-cmd --reload > /dev/null
else
   sudo sed -i 's/FW_SERVICES_EXT_TCP="/FW_SERVICES_EXT_TCP="9100 /g' /etc/sysconfig/SuSEfirewall2
   sudo systemctl restart SuSEfirewall2.service
fi

sleep 5

# Restarting node_exporter service
sudo systemctl daemon-reload
sudo systemctl start node_exporter.service
sleep 5

if sudo systemctl is-active --quiet node_exporter.service; then
   echo "Node exporter service is running"
else
   echo "Node exporter service is not running"
fi

exit