Goals:
- Run as root with a full bash env
- Notify on failure via SNS email
- Make this a good boilerplate
Sources:
Goals:
Sources:
| # Timer/Service Impl | |
| SERVICE_NAME="" | |
| SNS_TOPIC="" | |
| # Script-specific |
| #!/bin/bash | |
| chmod 700 script.sh | |
| # Ensure config has been set up | |
| ENV_FILE="$(dirname $0)/env" | |
| if [ ! -f "${ENV_FILE}" ]; then | |
| echo "File ${ENV_FILE} does not exist - please create before installing by copying from env.template and filling out!" | |
| exit 1 | |
| else | |
| echo "File ${ENV_FILE} exists." | |
| fi | |
| source "${ENV_FILE}" | |
| # Update unit path and name | |
| cp "$(dirname $0)/script.service" "$(dirname $0)/${SERVICE_NAME}.service" | |
| cp "$(dirname $0)/script.timer" "$(dirname $0)/${SERVICE_NAME}.timer" | |
| sed -i "s|^ExecStart=.*|ExecStart=/bin/bash $(dirname $0)/script.sh|" "$(dirname $0)/${SERVICE_NAME}.service" | |
| sed -i "s|SERVICE_NAME|${SERVICE_NAME}|g" "$(dirname $0)/${SERVICE_NAME}.service" | |
| sed -i "s|SERVICE_NAME|${SERVICE_NAME}|g" "$(dirname $0)/${SERVICE_NAME}.timer" | |
| # Apply units | |
| sudo mv "$(dirname $0)/${SERVICE_NAME}.service" "/etc/systemd/system/${SERVICE_NAME}.service" | |
| sudo chmod 644 "/etc/systemd/system/${SERVICE_NAME}.service" | |
| sudo mv "$(dirname $0)/${SERVICE_NAME}.timer" "/etc/systemd/system/${SERVICE_NAME}.timer" | |
| sudo chmod 644 "/etc/systemd/system/${SERVICE_NAME}.timer" | |
| sudo systemctl daemon-reload | |
| sudo systemctl enable "${SERVICE_NAME}.timer" |
| [Unit] | |
| Description=Execute a bash script for SERVICE_NAME | |
| [Service] | |
| Type=oneshot | |
| ExecStart= |
| #!/bin/bash | |
| source "$(dirname $0)/env" | |
| notify() { | |
| # Send notification | |
| aws sns publish --topic-arn "${SNS_TOPIC}" --message "$1" | |
| } | |
| handle_error() { | |
| notify "ERROR: ${SERVICE_NAME} failed on line ${LINENO}!" | |
| exit 1 | |
| } | |
| trap handle_error ERR | |
| # Example: 50/50 Success/Failure | |
| random_byte=$(od -An -N1 -t u1 /dev/urandom) | |
| if (( random_byte % 2 == 0 )); then | |
| result="True - Worked" | |
| else | |
| result="ERROR - False - Failed" | |
| exit 1 | |
| fi | |
| notify "OK: ${SERVICE_NAME} completed OK!" |
| [Unit] | |
| Description=Start the matching Systemd SERVICE_NAME.service on schedule | |
| [Timer] | |
| OnCalendar="Mon,Wed,Fri 1:0" | |
| Persistent=true | |
| [Install] | |
| WantedBy=timers.target |