Ansible for local/user services

Many of us have powerful workstations/computers running a good bit of the time that could be doing more useful work. We don’t have to deploy everything to the cloud. Tasks to consider running locally include:

  • backup scripts
  • maintenance scripts
  • CI/CD processes – especially those that require a lot of CPU power to run

We often don’t set up local services because it is tedious, and we don’t have a good way to automate it – especially across different users. If you are already using Ansible for server deployment, consider also using it to set up Systemd user services on your local machine. The advantages of this include:

  • don’t need root
  • automatically start when you log in
  • can leverage all your Ansible/Systemd knowledge you already have at the user account level
  • potentially more secure as workstations are behind firewalls and not directly accessible on the Internet

A few notes/tips:

  • user systemd services are stored in ~/.config/systemd/user
  • add --user to systemd commands. Examples:
    • systemctl --user start myservice
    • journalctl --user -f -u myservice
  • use %h to expand to home directory in systemd services.
  • use the default.target in user services

Example Systemd user service.

backup.service:

[Unit]
Description=backup service

[Service]
Environment=GOOGLE_APPLICATION_CREDENTIALS=%h/keys/backup-key.json
ExecStart=%h/bin/backup -retentionService

RestartSec=10
Restart=always

[Install]
WantedBy=default.target

Restart=always

[Install]
WantedBy=default.target

Local Ansible Playbook

A local role playbook might look something like:

local.yml:

- name: Playboop for localhost
  hosts: localhost
  roles:
    - backup-retention

And to run: ansible-playbook local.yml

Because it is localhost, no inventory file is needed.

Deploying to your local computer is the simplest scenario possible. And when possible, keep-it-simple!