大网数据广告活动
服务器运维问答

Creating an instance service file using an ansible template

· 52CE 我爱测

I have been using ansible for a while to install and configure several services, but this is the first time I am trying to set up a service that can have multiple instances running at the same time. I'm using a template for the s…

问题原文

原帖链接 · user3270760 · CC BY-SA 3.0

I have been using ansible for a while to install and configure several services, but this is the first time I am trying to set up a service that can have multiple instances running at the same time. I'm using a template for the service file, something like this:

[Unit]
Description=My Service
[Service]
WorkingDirectory=/var/lib/service/api
ExecStart=/usr/bin/python -O /var/lib/service/api/main.py -f /var/lib/service/api/cfg/service_api.cfg -p {{ port }}
Type=simple

And then my role for installing and configuring this service contains tasks like this:

- name: Configure api.service
  template: src=api.service.j2 dest=/etc/systemd/system/api@{{port}}.service

- name: Start service
  systemd: name=api@{{port}} state=restarted enabled=yes

Right now this is working for something like port = 80, but I don't think I made it generic enough. I don't fully understand how to create these instance services. How can I modify the service file and the role such that each listening port can have its own service file? Should I use the "Wants" keyword, or something like "WantedBy=multi-user.target"?

已采纳解答

原帖链接 · akavel · CC BY-SA 3.0

Rename your local file to api@.service (not api.service.j2) — we'll be using systemd templating instead of ansible's Jinja2 templating. Then change it like below:

[Unit]
Description=My Service on port %i
[Service]
...
ExecStart=... -p %i
...
[Install]
WantedBy=multi-user.target

Then you should be able to use it with ansible with a playbook like the following one:

- name: Deploy api@.service
  copy: src=api@.service dest=/etc/systemd/system/

- name: Start service
  systemd: name=api@{{item}} state=restarted enabled=yes
  with_items:
    - 80

(Though I'm not sure if it's better to use systemd or service module here; I'm still a newbie with ansible.)

See also: https://serverfault.com/a/730339/74509

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-11-30)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。