Managing service accounts in an RPM spec

I actually solved this independently, by looking at other RPM specs that did similar things. If you just want to add a user (conditionally), use Ignacio's link. I did this:

Requires(pre): /usr/sbin/useradd, /usr/bin/getent
Requires(postun): /usr/sbin/userdel

%pre
/usr/bin/getent group myservice || /usr/sbin/groupadd -r myservice
/usr/bin/getent passwd myservice || /usr/sbin/useradd -r -d /path/to/program -s /sbin/nologin myservice

%postun
/usr/sbin/userdel myservice

This makes sure that the RPM "cleans up after itself" but still provides the ability to install even if the account already exists.


Either of the two previous answers are production ready as those methods will delete the user if the package is upgrade. Yum installs the new package then removes the old package. This will leave you without an user. Not cool!

Use this method instead:

%postun
case "$1" in
   0) # This is a yum remove.
      /usr/sbin/userdel myservice
   ;;
   1) # This is a yum upgrade.
      # do nothing
   ;;
 esac

The response from Coderer is good but the second pre command give me an error on Centos 7. The group must be specified.

Requires(pre): /usr/sbin/useradd, /usr/bin/getent
Requires(postun): /usr/sbin/userdel

%pre
/usr/bin/getent group myservice > /dev/null || /usr/sbin/groupadd -r myservice
/usr/bin/getent passwd myservice > /dev/null || /usr/sbin/useradd -r -d /path/to/program -s /sbin/nologin -g myservice myservice

%postun
/usr/sbin/userdel myservice

I added also redirect to /dev/null to ignore unwanted echos.