Continuous deployment with Github Actions and systemd services
This is a collection of templates/scripts I use to set up CD systems for my projects.
For each project I deploy, I create a user and a systemd service. The user account's home directory is where the project lives, and the systemd service defines how it's run and ensures that it stays running after failure or reboot. The user is given sudo
permission only to interact with its own service, via a /etc/sudoers.d
supplement. The user account isn't accessible via password auth, but it does have an SSH key that can be used to log into the account and automate updates.
deploysetup.sh
automates this process. It creates a new user, configures its sudo and SSH permissions, generates an SSH key for it, and creates a template systemd service. After running the script, all I have to do is clone the project into the deploy user's home directory and configure the systemd service to run the project.
The actual CD is handled by a Github Actions workflow. This workflow is responsible for SSHing into the server as the deploy user, performing update tasks (checking out new code from git, updating local dependency installations, building artifacts, running database migrations, etc.), and restarting the service.
deploy.yml
is a template for this workflow which is configured to trigger on every push to the main branch. After copying it to the .github/workflows
folder of a repository, I script the necessary update tasks and copy information about the deploy server (hostname, user, private key) into repo secrets. Then, the workflow is triggered, it will connect to the server as the deploy user and carry out the script I've given it.