Working with services you can start, restart, stop and enable services from ansible.

Below example

sudo nano install-apache2-StopService.yml

Here I will install apache2 and then stop the apache2 service but enable the service.

---
- hosts: webservers
  become: true
  tasks:
  - name: install apache2
    tags: apache2
    apt:
      name: apache2
      state: latest
    when: ansible_distribution == 'Ubuntu'

- hosts: webservers
  become: true
  tasks:
  - name: stop apache2 service
    tags: apache2
    service:
      name: apache2
      state: stopped
      enabled: yes
    when: ansible_distribution == 'Ubuntu'
ansible-playbook --ask-become-pass install-apache2-StopService.yml

Now I will modify the .yml file from stopped to started, I have also modified the tag to apache2 and start so it wont try to install apache2 again.

---
- hosts: webservers
  become: true
  tasks:
  - name: install apache2
    tags: apache2
    apt:
      name: apache2
      state: latest
    when: ansible_distribution == 'Ubuntu'

- hosts: webservers
  become: true
  tasks:
  - name: start apache2 service
    tags: "apache2,start"
    service:
      name: apache2
      state: started
      enabled: yes
    when: ansible_distribution == 'Ubuntu'

running it with the tags so it only runs the service start in the playbook

ansible-playbook --tags "apache2,start" --ask-become-pass install-apache2-StopService.yml
sudo systemctl status apache2

By Kad

Leave a Reply

Your email address will not be published. Required fields are marked *