我正在尝试编写一个可行的剧本,它将nginx部署为一个podman容器,生成与所述容器相关的systemd单元,并启用&启动系统单元。容器本身创建得很好,并且已经启动并运行,但是系统无法识别创建的单元文件。创建容器后,可操作剧本的相关部分如下
---
- name: Create systemd script for created container
become: true
shell: podman generate systemd -n nginx --files
register: container_systemd_file
- name: Get service name
set_fact:
service_name: "{{ container_systemd_file.stdout | basename }}"
- name: Move created systemd script to correct location
become: true
shell: mv {{ container_systemd_file.stdout }} /etc/systemd/system/
- name: Force systemd to reread configs
become: true
systemd: daemon_reload=yes
- name: Enable nginx container service
become: true
systemd:
name: "{{ service_name }}"
enabled: true
state: started
最后一步失败,消息为"msg": "Could not find the requested service container-nginx.service: host"
。
可以在主机上找到单元文件
$ ls -al /etc/systemd/system/container-nginx.service
-rw-r--r--. 1 root root 701 Sep 24 15:19 /etc/systemd/system/container-nginx.service
并有内容
# container-nginx.service
# autogenerated by Podman 3.2.3
# Fri Sep 24 15:19:41 EEST 2021
[Unit]
Description=Podman container-nginx.service
Documentation=man:podman-generate-systemd(1)
Wants=network.target
After=network-online.target
RequiresMountsFor=/var/run/containers/storage
[Service]
Environment=PODMAN_SYSTEMD_UNIT=%n
Restart=on-failure
TimeoutStopSec=70
ExecStart=/usr/bin/podman start nginx
ExecStop=/usr/bin/podman stop -t 10 nginx
ExecStopPost=/usr/bin/podman stop -t 10 nginx
PIDFile=/var/run/containers/storage/overlay-containers/c5ad5d961913a8d48ea09557484eaf17749086581eb5a1750e65fb4cf8965272/userdata/conmon.pid
Type=forking
[Install]
WantedBy=multi-user.target default.target
同样,如果我运行systemctl daemon-reload并尝试在主机上手动启用该服务,它会失败,并显示Failed to enable unit: Unit file container-nginx.service does not exist.
如何使系统识别新创建的单元文件并启用服务?我使用的是Podman 3.2.3和RHEL 8.4。
我无法弄清楚为什么最初的方法不起作用,而是首先将systemd单元作为文件生成到用户的主目录,然后移动它,直接在/etc/systemd/system/
下写文件工作。
---
- name: Create systemd script for created container
become: true
shell: podman generate systemd --new --name nginx > /etc/systemd/system/nginx.service
- name: Force systemd to reread configs
become: true
systemd: daemon_reload=yes
- name: Enable nginx container service
become: true
systemd:
name: nginx.service
enabled: true
state: started
实际上,正确的答案是你什么都不做。只要.container
文件在其Install
部分中有一些WantedBy
,它将在.service
文件的再生(或重新启动)时自动启用。
详细说明见https://github.com/containers/podman/issues/17567