简体   繁体   中英

Start many processes using systemd ansible

I want to start N processes with the systemd module, let's suppose I have the following service:

# file: /etc/systemd/system/sleep@.service
[Service]
ExecStart=/bin/sleep 420

[Install]
WantedBy=multi-user.target

I want to start 3 processes with the systemd module:

- name: Start Systemd Unit
  systemd:
    name: 'sleep@{1..3}.service'
    state: 'started'

The task above creates only one encoded process sleep@\\x7b1..3\\x7d.service , I can't figure out how to not encode the string. Does ansible support creating multiple processes? if not, what is the easiest way to do so?


My current workaround defines a list of services that have an instances key, using the subelements I'm able to create those processes separately. I think there is a better way to it.

app_systemd_services:
  - name: sleep
    instances: "{{ range(3) | list }}"
- name: Ensure Systemd Units are started
  systemd:
    name: "{{ item.0.name }}@{{ item.1 }}.service"
    state: started
  loop: "{{ app_systemd_services | subelements('instances') }}" 

Ansible does not support ranges (...). Use with_items .

- name: Start Systemd Unit
  systemd:
    name: 'sleep@{{ item }}.service'
    state: started
  with_items:
    - 1
    - 2
    - 3

One more unsolicited advice. If you use templates for systemd, use .target unit with dependency.

Template for foo@.service should say Wanted-by: foo.target , and than you can manage them by systemctl stop/start/restart foo.target .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM