Ansible roles workflow issue

181 Views Asked by At

I want to (step1) change postgresql configuration file, (step2) restart service and then (step3) add db user.

../roles/postgres/tasks/main.yml

- name: change postgre pg_hba.conf
  template: src=pg_hba.conf.j2 dest=/etc/postgresql/9.4/main/pg_hba.conf 
  notify: restart postgresql service
  tags: pg_hba

- name: set password for postgres
  postgresql_user:
    db: postgres
    user: postgres
    password: postgres

../roles/postgres/handlers/main.yml

---
- name: restart postgresql service
  service: name=postgresql state=restarted enabled='yes'

postgres.yml

- hosts: postgresql_server
  remote_user: ubuntu
  become: true
  become_method: sudo
  become_user: root

  roles:
    - role: postgres

Problem: The real workflow in ansible roles is: step1 -> step3 -> step2.

I can fix it by moving handlers task into ../roles/postgres/tasks/main.yml, but it will restart service no matter whether configuration file was changed.

What's the best practice for such request?

1

There are 1 best solutions below

1
On

Flush handlers with meta: flush_handlers before the task that requires it:

- name: change postgre pg_hba.conf
  template: src=pg_hba.conf.j2 dest=/etc/postgresql/9.4/main/pg_hba.conf 
  notify: restart postgresql service
  tags: pg_hba

- meta: flush_handlers

- name: set password for postgres
  postgresql_user:
    db: postgres
    user: postgres
    password: postgres