Creating a SystemD service to run a self hosted devops agent.
I have the need to run an Azure Devops Agent as a systemD. Typcially I would just run it inside a container. But due to requirements on this system and pipeline I am unable to simply run inside a container. The belows assumes you have an agent already setup. Lets get started.
Creating the service file
First, lets go over the structure of a systemd service file.
There are three important sections. They are [Unit], [Service], and [Install]. The extension is .service and we can make comments with the hash symbol(#).
Lets create a file
[Unit]
Description=Devops Service
After=multi-user.target
[Service]
ExecStart=/home/[username]/myagent/run.sh
WorkingDirectory=/home/[username]/myagent/
User=opc
Group=opc
Restart=always
Type=simple
[Install]
WantedBy=default.target
What does each section do?
The [Unit] section helps describe the service and when to start it. In this case we want to ensure the network is up before starting the service. You can include an [Before] section to ensure the service starts before another service.
The [Service] section contains details about what we want it to execture and how to terminate.
The [Install] section tells the system how to handle the installation of the file. This is ran when you run systemctl enable/disable.
Now the fun part, installing the service.
We need to place the file under /etc/systemd/system. Use your favorite text editor and save it in the path above.
Enabling the service
Tell the system to read the files. The below command will make systemd aware that it exists.
sudo systemctl daemon-reload
Now we need to enable the service. I saved my file as devops.service. Using that file name we will run the below command.
sudo systemctl enable devops.service
This creates symlinks to the correct directories to allow systemd to start the service at the correct time.
We can start the service with the below command.
sudo systemctl start devops
SELinux
SELinux restricts where SystemD can execute scripts. If you have problems loading your script,
View the logs with the below command.
sudo journalctl -xe
If SELinux is preventing anything, you should see a log in red stating:
SELinux is preventing (run.sh) from execute access on the.....
You can fix this by moving the folder to an approved location or telling SystemD to allow this path.
sudo chcon -R -t bin_t /home/opc/myagent/
Following these steps will allow you to start the service automatically on system reboot.