Managing service accounts in an RPM spec

I've been given a partially-complete RPM spec for a service we're writing. It gets as far as making the required directories, copying files, setting permissions, etc., but it doesn't make the required system account that the service will run under. I was told that it's best for the RPM to take care of this, so I've added

Requires(pre): /usr/sbin/useradd

%pre
useradd -r -d /path/to/program -s /bin/false myservice

This succeeds in making the user account (and associated group), so later on when it tries to set ownership / permissions on the service's files, that succeeds as well.

My current problem is, a) if the user account already exists, the RPM install fails because useradd fails (because the user already exists); and b) I don't know how to have rpm -e myservice also remove the associated user and group.


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