Thursday, April 1, 2021

Creating a Scheduled SystemD Service

This post was generated from a document I wrote for another team to assist them in creating a service that could be scheduled and logged by SystemD.

SystemD Unit Files

You'll put these files will be located in "/usr/lib/systemd/system/".
The .service file will look like this:
[Unit]
Description=Execute My Script

[Service]
User=admin
Group=admin
ExecStart=/srv/scripts/myScript.sh

[Install]
WantedBy=default.target
The name of the .service file is arbitrary, and can be named anything. If you call it "myService.service", then you can invoke it like this:
$ sudo systemctl start myService
Make sure your "ExecStart=" statement value corresponds to the script in the location you want it.
The .timer file looks like this:
[Unit] 
Description=Execute myService Daily at 1215 UTC

[Timer]
OnCalendar=*-*-* 12:15:00
Unit=myService.service

[Install]
WantedBy=default.target
Again, the name is arbitrary. I named mine "myService.timer", which made it simple to pair with my .service file.
The time listed is for a 1215 UTC execution, which is because my server's system time was set to UTC. Make sure you list the name of your .service file in the "Unit=" statement.
You would then enable the timer like this:
$ sudo systemctl enable myService.timer

SELinux

Chances are that the stuff above will all be thwarted by SELinux, for better or worse. It's going to take a few commands to get that squared away.
In my example, the location of the scripts are in "/srv/scripts", and the SystemD unit files are named "myService.service" and "myService.timer". Change this to meet whatever your system reflects.
For the scripts:
# semanage fcontext -a -t bin_t "/srv/scripts(/.*)?"

# restorecon -R -v /srv/scripts
For the SystemD Unit Files:
# semanage fcontext -a -t systemd_unit_file_t /usr/lib/systemd/system/myService.*

# restorecon -R -v /usr/lib/systemd/system
Obviously, these are being run as the root user. The "semanage" command is setting the SELinux file context on each set of files to the appropriate type, and the "restorecon" command is registering the change with the running SELinux subsystem.
 
 
Edited:  10 April 2021

No comments:

Post a Comment

What is Commercially-Available Information (CAI)?

I'm working on some thoughts about the ODNI report on Federal Agencies purchasing Commercially-Available Information (CAI for short), an...