Raspberry Pi - Create a system service

I needed a way of creating a system service to automagically start a k3s agent when the node booted up.

  1. Create a .service file and a .py file for the python script with the following content.

startk3sagent.service

1
sudo nano startk3sagent.service
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[Unit]
Description=Service to start K3S Agent as part of cluster
After=network.target

[Service]
ExecStart=/usr/bin/python3 -u startk3sagent.py
WorkingDirectory=/home/pi/k3sscripts
StandardOutput=inherit
StandardError=inherit
Restart=always
User=pi

[Install]
WantedBy=multi-user.target

startk3sagent.py

1
2
3
mkdir k3sscripts
cd k3sscripts
sudo nano startk3sagent.py
1
2
3
4
5
6
7
8
import os

K3S_URL="https://192.168.1.79:6443"
K3S_TOKEN="K10604bc55a643203542d97aafd91b0b0c2dc4233d46a1dc3a20a8f4ccf7d16fb50::server:09149feb4ee470a2eff3d3d1e4a83c43"

COMMAND = "sudo k3s agent --server " + K3S_URL + " --token " + K3S_TOKEN

os.system(COMMAND)
  1. Copy the file and test it works
1
2
3
sudo cp startk3sagent.service /etc/systemd/system/startk3sagent.service     ~ copy file
sudo systemctl start startk3sagent.service ~ start service
sudo systemctl stop startk3sagent.service ~ stop service
  1. Install as a service
1
2
3
sudo systemctl enable startk3sagent.service

Created symlink /etc/systemd/system/multi-user.target.wants/startk3sagent.service → /etc/systemd/system/startk3sagent.service.
  1. Check what services are running
1
sudo service --status-all

References