Skip to content

Commit

Permalink
Add user-data script for installing service on a cloud provider VM
Browse files Browse the repository at this point in the history
The script will:
1. Install necessary dependencies
2. Create the DB file
3. Run the migrations
4. Initialize the DB with the seed data
5. Move the systemd unit file to the correct location
6. Enable the systemd service

The script will NOT:
- Create the `.env` file
- Start the server (the systemd service will start the server on reboot tho)
  • Loading branch information
szabolcs-horvath committed Jan 3, 2025
1 parent 456d28c commit 96bf92e
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
7 changes: 7 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ HTMX_VERSION ?= 2.0.3
BOOTSTRAP_VERSION ?= 5.3.3
BOOTSTRAP_ICONS_VERSION ?= 1.11.3

install: install-go-deps init-db build
mv -u prod/nutrition-tracker.service /etc/systemd/system/nutrition-tracker.service
systemctl enable nutrition-tracker.service

start:
systemctl start nutrition-tracker.service

install-go-deps:
go install -v github.com/sqlc-dev/sqlc/cmd/sqlc@$(SQLC_VERSION)
go install -v -tags 'sqlite3' github.com/golang-migrate/migrate/v4/cmd/migrate@$(GOLANG_MIGRATE_VERSION)
Expand Down
19 changes: 19 additions & 0 deletions prod/nutrition-tracker.service
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
[Unit]
Description=Nutrition Tracker server
ConditionFileNotEmpty=~/nutriton-tracker/.env
ConditionPathExists=~/nutriton-tracker/sqlite/nutrition-tracker.db
After=multi-user.target
Wants=multi-user.target
StartLimitIntervalSec=600
StartLimitBurst=5

[Service]
Type=simple
ExecStartPre=/bin/bash -c 'echo "$(date +"%%F-%%T") starting" >> /var/log/nutrition-tracker-starts.log'
ExecStart=/bin/bash -c '~/nutriton-tracker/out/nutrition-tracker ~/nutriton-tracker/.env 2>&1 | tee /var/log/nutrition-tracker.log && exit ${PIPESTATUS[0]}'
ExecStartPost=/bin/bash -c 'echo "$(date +"%%F-%%T") started" >> /var/log/nutrition-tracker-starts.log'
Restart=on-failure
TimeoutSec=30

[Install]
WantedBy=multi-user.target
20 changes: 20 additions & 0 deletions prod/user-data.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#!/bin/bash

# logging
exec >> /var/log/user-data.log
exec 2>&1

set -ex -o pipefail

main() {
if [[ ! -d ~/nutrition-tracker ]]; then
cd ~
git clone https://github.com/szabolcs-horvath/nutrition-tracker.git
cd nutrition-tracker
make install
else
echo "Nutrition Tracker already installed."
fi
}

main "$@"

0 comments on commit 96bf92e

Please sign in to comment.