如何正确地将 systemd 服务添加到 cpack 生成的 debian 包中?

How to correctly add a systemd service to a cpack generated debian package?

我正在尝试通过 cpack 生成一个符合系统配置的 debian 包(如在管理员不希望的情况下不要启动该服务)并且在安装时不会导致错误systemd 免费环境(如某些 docker 图像)。

我当前的设置由一个 postinst 和一个 prerm 文件组成,它们很容易通过 CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA 提供给 cpack。 这些在两个脚本中调用 systemctl enable/start/stop/disable

根据我收集到的信息,应该调用 dh_installsystemd --name=foo foo.service 来启动服务。

systemctl enable foo.service 替换为我的 postinst 文件中的内容会导致错误:

dh_installsystemd: error: "debian/control" not found. Are you sure you are in the correct directory?
dpkg: error processing package foo (--configure):
 installed foo package post-installation script subprocess returned error exit status 255
Processing triggers for libc-bin (2.31-0ubuntu9.2) ...
Errors were encountered while processing:
 foo

我必须承认,对于应该如何处理这件事,我有些迷茫。 如何通过 CPack 正确地将 systemd 服务添加到 debian 包?

想到的最佳解决方案是剖析另一个包并使用 dh_installsystemd 生成的相同命令。

这会生成如下的 postinst 文件:

# End automatically added section
# Based on output by dh_installsystemd/13.5.2

if [ \"\" = \"configure\" ] || [ \"\" = \"abort-upgrade\" ] || [ \"\" = \"abort-deconfigure\" ] || [ \"\" = \"abort-remove\" ] ; then

    # was-enabled defaults to true, so new installations run enable.
    if deb-systemd-helper --quiet was-enabled 'foo.service'; then
        # Enables the unit on first installation, creates new
        # symlinks on upgrades if the unit file has changed.
        deb-systemd-helper enable 'foo.service' >/dev/null || true
    else
        # Update the statefile to add new symlinks (if any), which need to be
        # cleaned up on purge. Also remove old symlinks.
        deb-systemd-helper update-state 'foo.service' >/dev/null || true
    fi
fi
if [ \"\" = \"configure\" ] || [ \"\" = \"abort-upgrade\" ] || [ \"\" = \"abort-deconfigure\" ] || [ \"\" = \"abort-remove\" ] ; then
    if [ -z \"${DPKG_ROOT\:-}\" ] && [ -d /run/systemd/system ]; then
        systemctl --system daemon-reload >/dev/null || true
        deb-systemd-invoke restart 'foo.service' >/dev/null || true
    fi
fi

由于这些指令是宏中的静态更新,因此必须手动应用。