How to create directory and change it's owner with the deb package

You were right, you need a debian/my_package.postinst file to perform such operation:

#!/bin/sh

#DEBHELPER#

set -e

DIR="/var/log/my_package/"
USER="my_user"

mkdir -p ${DIR}    
if id -u ${USER} > /dev/null 2>&1; then    
    chown ${USER}:${USER} ${DIR}
fi

Note: The script checks if the user exists before calling chown.


You do not need to create a postinst script, but the solution is still a bit tricky. I use dh wildcard in debian/rules:

#!/usr/bin/make -f
%:
        dh $@

binary:
        dh $@

which does all the needed stuff. But I need to override some dir's ownership (lets call it data). So I must make some exception, I use special directives as follow:

    override_dh_install:
        dh_install   #calls default *.install and *.dirs installation
        install -d -o www-data -g www-data $(CURDIR)/debian/<package_name>/var/www/<something>/data 

The data directory do not need to be in *.dirs file. But still there is one trick. Debhelper contains script dh_fixperms, which would fix ownership back to root, so we need to override too:

override_dh_fixperms:
    dh_fixperms --exclude data

That's all. Keep in mind the data dir does not count as a conffile, so it will be removed on package removal. If you need to make it a conffile, it is another story.