在启动操作系统时,使用systemd执行任意的程序

我想做的事情是:我希望在CentOS7启动时只执行一次Chef。

在CentOS 7中,服务管理已经从init脚本变为systemd。在init脚本中,我们可以将命令写在/etc/rc.d/rc.local文件中,在操作系统启动时自动执行,但在systemd中似乎有所不同,所以我进行了调查(虽然有点晚)。

尽管CentOS7中也有/etc/rc.d/rc.local文件,但是查看其内容如下。

#!/bin/bash
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.

touch /var/lock/subsys/local

所以,建议您自己创建systemd服务或编写udev规则。

写了一篇文章。
如果将/etc/systemd/system/chef-client.service放置并执行systemctl daemon-reload,该服务将被注册。

[Unit]
Description=run Chef Client during boot
After=network.target

[Service]
Type=simple
RemainAfterExit=yes
ExecStart=/bin/chef-client -z

[Install]
WantedBy=multi-user.target

作为要点,在Unit部分的After后面,定义了希望先启动的服务。另外,在Type中写明了启动过程的类型。当Type=simple时,命令执行完成后即认为启动完成。当Type=oneshot时,在指定的命令完成后判断为启动完成和服务结束。如果希望在命令完成后仍将其识别为启动状态的服务,则需指定RemainAfterExit=yes。

请查看man页以获取.service文件的详细信息。
http://www.freedesktop.org/software/systemd/man/systemd.service.html

启动设置、行动确认

[root@centos7-01 chef]# systemctl daemon-reload
[root@centos7-01 chef]# systemctl enable chef-client
[root@centos7-01 chef]# systemctl stop chef-client
[root@centos7-01 chef]# systemctl start chef-client
[root@centos7-01 chef]# systemctl status chef-client
● chef-client.service - Chef Client
   Loaded: loaded (/etc/systemd/system/chef-client.service; disabled; vendor preset: disabled)
   Active: active (exited) since Fri 2016-01-29 19:05:52 EST; 7s ago
  Process: 6397 ExecStart=/bin/chef-client -z (code=exited, status=0/SUCCESS)
 Main PID: 6397 (code=exited, status=0/SUCCESS)

Jan 29 19:05:51 centos7-01 chef-client[6397]: [2016-01-29T19:05:51-05:00] INFO: Starting Chef Run for centos7-01
Jan 29 19:05:51 centos7-01 chef-client[6397]: [2016-01-29T19:05:51-05:00] INFO: Running start handlers
Jan 29 19:05:51 centos7-01 chef-client[6397]: [2016-01-29T19:05:51-05:00] INFO: Start handlers complete.
Jan 29 19:05:51 centos7-01 chef-client[6397]: [2016-01-29T19:05:51-05:00] INFO: HTTP Request Returned 404 Not Found: Object not found:
Jan 29 19:05:51 centos7-01 chef-client[6397]: [2016-01-29T19:05:51-05:00] INFO: Loading cookbooks []
Jan 29 19:05:51 centos7-01 chef-client[6397]: [2016-01-29T19:05:51-05:00] WARN: Node centos7-01 has an empty run list.
Jan 29 19:05:51 centos7-01 chef-client[6397]: [2016-01-29T19:05:51-05:00] INFO: Chef Run complete in 0.053521516 seconds
Jan 29 19:05:51 centos7-01 chef-client[6397]: [2016-01-29T19:05:51-05:00] INFO: Running report handlers
Jan 29 19:05:51 centos7-01 chef-client[6397]: [2016-01-29T19:05:51-05:00] INFO: Report handlers complete
Jan 29 19:05:52 centos7-01 systemd[1]: Started Chef Client.

看起来运行良好!