Search code examples
ansibleansible-role

problem with task Ensure that Nginx is stopped


I wrote a role to run the reactos application the problem occurs with a single task to Ensure that Nginx is stopped . I get a strange error

enter image description here

if I remove this point from the role, the application closes successfully, but I would like it to work with it as well previous task works good

- name: Ensure nginx is not installed
  apt:
    name: nginx
    state: absent

but this doesnt work

- name: Ensure that Nginx is stopped
  ansible.builtin.systemd:
    name: nginx
    state: stopped

how to solve the problem


Solution

  • Use service. It is compatible in most use cases.

    Service - Controls services on remote hosts. Supported init systems include BSD init, OpenRC, SysV, Solaris SMF, systemd, upstart.

    https://docs.ansible.com/ansible/latest/collections/ansible/builtin/service_module.html

    ---
    
    - hosts: localhost
      gather_facts: false
      become: true
      tasks:
        - name: Ensure nginx is installed
          apt:
            name: nginx
            state: latest
    
        - name: service started
          service:
            name: nginx
            state: started
    
        - name: service stopped
          service:
            name: nginx
            state: stopped
    

    sysvinit - Controls services on target hosts that use the SysV init system. https://docs.ansible.com/ansible/latest/collections/ansible/builtin/sysvinit_module.html

    ---
    
    - hosts: localhost
      gather_facts: false
      become: true
      tasks:
        - name: Ensure nginx is installed
          apt:
            name: nginx
            state: latest
    
        - name: sysvinit started
          sysvinit:
            name: nginx
            state: started
    
        - name: sysvinit stopped
          sysvinit:
            name: nginx
            state: stopped
    

    Systemd Requirements: A system managed by systemd. https://docs.ansible.com/ansible/latest/collections/ansible/builtin/systemd_module.html

    ---
    
    - hosts: localhost
      gather_facts: false
      become: true
      tasks:
        - name: Ensure nginx is installed
          apt:
            name: nginx
            state: latest
        
        # this one fails
        - name: systemd started - fail
          systemd:
            name: nginx
            state: started
    
        # this one fails
        - name: systemd stopped - fail
          systemd:
            name: nginx
            state: stopped