---
- name: Apache sites checked, disabled and enabled
  block:

    - name: Check loaded sites
      block:

        - name: Register the loaded sites
          command: a2query -s
          check_mode: false
          changed_when: false
          register: apache_sites_check

      rescue:

        - name: No sites enabled
          set_fact:
            apache_sites_loaded: []
          when: ( "No site matches" in apache_sites_check.stderr )

    - name: Debug the loaded sites
      debug:
        var: apache_sites_check.stdout_lines
        verbosity: 2
      when: apache_sites_check.stdout is defined

    - name: Set an array of the loaded sites
      set_fact:
        apache_sites_loaded: "{{ apache_sites_loaded | default([]) + [ line.split(' ')[0] ] }}"
      when: apache_sites_check.stdout is defined
      loop: "{{ apache_sites_check.stdout_lines }}"
      loop_control:
        loop_var: line
        label: "{{ line }}"

    - name: Debug loaded sites
      debug:
        var: apache_sites_loaded
        verbosity: 2
      when: apache_sites_loaded is defined

    - name: Apache sites disabled
      command: "a2dissite {{ site }}"
      args:
        removes: "/etc/apache2/sites-enabled/{{ site }}.conf"
      when:
        - apache_sites_disabled is defined
        - apache_sites_disabled != []
        - site in apache_sites_loaded
      loop: "{{ apache_sites_disabled }}"
      loop_control:
        loop_var: site
        label: "{{ site }}"

    - name: Apache site enabled
      block:

        - name: Apache sites enabled
          command: "a2ensite {{ site }}"
          args:
            creates: "/etc/apache2/sites-enabled/{{ site }}.conf"
          when:
            - apache_sites_enabled is defined
            - apache_sites_enabled != []
            - site not in apache_sites_loaded
          loop: "{{ apache_sites_enabled }}"
          loop_control:
            loop_var: site
            label: "{{ site }}"

      rescue:

        - name: Site enable failed
          debug:
            msg: Enabing an Apache site failed, check that the files exists in /etc/apache2/sites-available

  tags:
    - apache
...
