Mrunal Gosar
Mrunal Gosar

Reputation: 4683

ansible run command on remote host in background

I am trying to start filebeat (or for that matter any other process which will run continuously on demand) process on multiple hosts using ansible. I don't want ansible to wait till the process keeps on running. I want ansible to fire and forget and come out and keep remote process running in back ground. I've tried using below options:

    ---
    - hosts: filebeat
      tasks:
      - name: start filebeat
option a)  command: filebeat -c filebeat.yml &
option b)  command: nohup filebeat -c filebeat.yml &
option c)  shell: filebeat -c filebeat.yml &
           async: 0 //Tried without as well. If its > 0 then it only waits for that much of time and terminates the filebeat process on remote host and comes out.
           poll: 0

Upvotes: 39

Views: 76493

Answers (2)

deFreitas
deFreitas

Reputation: 4448

I preferred to start the command as a service

- name: Install my Service
  template:
    src: my-service.service
    dest: /etc/systemd/system/my-service.service
    mode: '0644'

- name: Configuring my service
  systemd:
    name: my-service.service
    enabled: yes
    state: started
    daemon_reload: yes

my-service.service

[Unit]
Description=K3s Cluster Start Service
After=network.target

[Service]
ExecStart=/usr/local/bin/my-command.sh {{some_ansible_var}}
Restart=always
User=root
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=k3s

[Install]
WantedBy=multi-user.target

Upvotes: 0

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68289

Simplified answer from link I mentioned in the comment:

---
- hosts: centos-target
  gather_facts: no
  tasks:
    - shell: "(cd /; python -mSimpleHTTPServer >/dev/null 2>&1 &)"
      async: 10
      poll: 0

Note subshell parentheses.

Update: actually, you should be fine without async, just don't forget to redirect stdout:

- name: start simple http server in background
  shell: cd /tmp/www; nohup python -mSimpleHTTPServer </dev/null >/dev/null 2>&1 &

Upvotes: 73

Related Questions