Score:1

Syntax error in ansible while using handlers

sj flag

Below is my role task which copied the nginx conf and then reloads the service only when the shell command output of nginx -t contains "syntax is ok"

---
# tasks file for nginx
- name: Backup and update nginx configuration file
  template:
     src: templates/proxy.conf.j2
     dest: "{{ nginx_conf }}"
     backup: true
     owner: root
     group: root
     mode: 0644

  

- name: Running nginx -t to validate the config
  shell: 'nginx -t'
  register: command_output
  become: true
  notify: Reload nginx

- debug:
   var: command_output.stderr_lines

  handlers:
    - name: Reloading nginx service only if the syntax is ok
      systemd:
        name: nginx.service
        state: reloaded'
        when: command_output.stderr | regex_search("syntax is ok")

Below is the error msg while doing a syntax check, but if I comment out the handlers section, it works fine..

ERROR! conflicting action statements: debug, handlers

The error appears to be in '/home/ansible/mint-ansible/nginx/tasks/main.yaml': line 20, column 3, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:


- debug:
  ^ here
Score:1
in flag

Handlers belong into their own subdirectory in a role

- rolename
  |- tasks
  |  `- main.yml
  `- handlers
     `- main.yml
Vicky Ingle - Mint avatar
sj flag
quick thing, if I move the handler code to separate dir, will the when condition work ? when: command_output.stderr | regex_search("syntax is ok") or shall I add this when condition in the 2nd task "name: Running nginx -t to validate the config" ??
in flag
No. You should ask a separate question about that. That would be too complex to be answered in comments.
in flag
But it wouldn't have worked the way you have it now anyway.
Vicky Ingle - Mint avatar
sj flag
https://serverfault.com/questions/1118365/need-to-know-more-about-the-handlers-in-ansible
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.