从 Ansible Playbook 启动 systemd 服务

从 Ansible Playbook 启动 systemd 服务

必须使用什么特定语法才能使 Ansible playbook 成功启动 systemd 服务并确保 systemd 服务在 Amazon EC2 实例上运行?

当前语法:

Ansible Playbook 中的以下语法在 Playbook 运行时成功通过,但随后我们发现,myapp.service当我们将其放入 EC2 实例进行检查时,该语法随后未运行:

- name: create the myapp service file.
  shell:
    cmd: |
      cat << 'EOF' >> /usr/lib/systemd/system/myapp.service
      [Unit]
      Description=myapp service
      After=syslog.target
      After=network.target
      [Service]
      User=myapp-host
      Type=simple
      ExecStart=/bin/sh -c 'cd /home/myapp-host/myapp-files/ && /home/myapp-host/bin/bundle exec myapp serve --source /home/myapp-host/myapp-files/'
      Restart=always
      StandardOutput=syslog
      StandardError=syslog
      SyslogIdentifier=myapp
      [Install] 
      WantedBy=multi-user.target
      EOF
  args:
    executable: /bin/bash
  become: true
  become_user: root
  vars:
    ansible_become_password: "{{ root_pass_myapp }}"

- name: Make sure myapp service is running
  systemd:
    state: started
    name: myapp
  become: true
  become_method: sudo
  become_user: root
  vars:
    ansible_become_password: "{{ root_pass_myapp }}"  

当前失败的结果:

接下来,当我们输入 EC2 实例时,我们得到以下结果systemctl status myapp.service

[myapp-host@ip-12-3-4-56 ~]$ sudo systemctl status myapp.service
● myapp.service - myapp service
   Loaded: loaded (/usr/lib/systemd/system/myapp.service; enabled; vendor preset: disabled)
   Active: failed (Result: start-limit) since Wed 2020-10-21 22:33:25 UTC; 2min 10s ago
  Process: 19716 ExecStart=/bin/sh -c cd /home/myapp-host/myapp-files/ && /home/myapp-host/bin/bundle exec myapp serve --source /home/myapp-host/myapp-files/ (code=exited, status=127)
 Main PID: 19716 (code=exited, status=127)

Oct 21 22:33:25 ip-12-3-4-56.aws-region-n.compute.internal systemd[1]: myapp.service: main process exited, code=exited, status=127/n/a
Oct 21 22:33:25 ip-12-3-4-56.aws-region-n.compute.internal systemd[1]: Unit myapp.service entered failed state.
Oct 21 22:33:25 ip-12-3-4-56.aws-region-n.compute.internal systemd[1]: myapp.service failed.
Oct 21 22:33:25 ip-12-3-4-56.aws-region-n.compute.internal systemd[1]: myapp.service holdoff time over, scheduling restart.
Oct 21 22:33:25 ip-12-3-4-56.aws-region-n.compute.internal systemd[1]: start request repeated too quickly for myapp.service
Oct 21 22:33:25 ip-12-3-4-56.aws-region-n.compute.internal systemd[1]: Failed to start myapp service.
Oct 21 22:33:25 ip-12-3-4-56.aws-region-n.compute.internal systemd[1]: Unit myapp.service entered failed state.
Oct 21 22:33:25 ip-12-3-4-56.aws-region-n.compute.internal systemd[1]: myapp.service failed.
[myapp-host@ip-12-3-4-56 ~]$  

答案1

答案很简单。只需source /etc/profile在命令中添加ExecStart如下即可解决该错误:

ExecStart=/bin/sh -c 'source /etc/profile && cd /home/myapp-host/myapp-files/ && /home/myapp-host/bin/bundle exec myapp serve --source /home/myapp-host/myapp-files/'

相关内容