Last active
March 22, 2019 09:22
-
-
Save simcap/59da0b382e677796e4482b4246938f41 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash -e | |
# | |
# This script is a utility to provision easily a Linux machine with a new GO service. | |
# 1. Ensure the application home exists | |
# 2. Create a new systemd service file for given service's name | |
# 3. Create the symlink from the service name to the actual binary | |
# 4. Enable the systemd service (i.e. service restart on machine boot) | |
# 5. Reload the systemd daemon | |
APPS_HOME=~/goapps | |
SYSTEMD_DIR=/etc/systemd/system | |
usage(){ | |
echo "USAGE: | |
`basename $0` -s <service> | |
Options: | |
-s <service> Name of the new systemd service (i.e. GO app)" | |
exit | |
} | |
if [ "$#" -ne 2 ] || [ "$1" == "--help" ] || [ "-h" == "$1" ]; then | |
usage | |
exit 0 | |
fi | |
SERVICE_NAME=$2 | |
SERVICE_HOME=$APPS_HOME/$SERVICE_NAME | |
SERVICE_FILE=$SYSTEMD_DIR/$SERVICE_NAME.service | |
SYMLINKED_BIN_NAME=$SERVICE_NAME-service | |
if [ -f $SERVICE_FILE ]; then | |
echo "Systemd service definition file $SERVICE_FILE exists already!" | |
echo "Exiting..." | |
exit 0 | |
fi | |
sudo mkdir -p $SERVICE_HOME | |
echo "Running for service name $SERVICE_NAME" | |
echo " [+] Created service home: $SERVICE_HOME" | |
sudo bash -c "cat > $SERVICE_FILE" << EOF | |
[Unit] | |
Description=$SERVICE_NAME GO service | |
After=network.target | |
[Service] | |
Environment=MY_VAR=true | |
SyslogIdentifier=$SERVICE_NAME-service | |
ExecStart=${SERVICE_HOME}/${SYMLINKED_BIN_NAME} | |
Restart=on-failure | |
[Install] | |
WantedBy=multi-user.target | |
EOF | |
echo " [+] Created systemd service file: $SERVICE_FILE" | |
sudo systemctl enable $SERVICE_FILE | |
echo " [+] Enabled $SERVICE_NAME systemd service to restart automatically on machine boot" | |
sudo ln -fs ${SERVICE_HOME}/${SERVICE_NAME} ${SERVICE_HOME}/${SYMLINKED_BIN_NAME} | |
echo " [+] Created symlink to binary file" | |
sudo systemctl daemon-reload | |
echo " [+] Reload systemd daemon" | |
echo | |
echo "Useful service commands: | |
$ sudo systemctl status $SERVICE_NAME | |
$ sudo systemctl restart $SERVICE_NAME | |
$ sudo systemctl stop $SERVICE_NAME | |
$ sudo systemctl start $SERVICE_NAME | |
$ journalctl -u $SERVICE_NAME # tail application logs" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment