1

I am looking for a way to execute some actions before and after each role has run. pre_tasks and post_tasks look like a good candidate, but I have found no way to include them transparently for all defined roles/playbooks. I don't want to add these manually to all playbooks since this seems like a maintenance nightmare.

Another angle to solve this might be to abuse the fact that Ansible logs in via ssh. However I am not aware of any identifying properties of an Ansible login as opposed to a regular user login.

My specific issue is: I want to trigger etckeeper before and after each execution of a role.

If you have any other "out-of-the-box" ideas to solve this, I will be grateful to hear them.

1
  • Long shoot (and this should be a comment really). Create another role with a task for the pre and a handler for the post than add the role as a dependency (in meta/main.yml) to the other roles. The dependencies are executed only once and with any luck the handlers will be executed at the end. It’s not exactly what you’re looking for but it’s close.
    – boca
    Oct 29 '20 at 13:48
1

Not tested this, but is include_role any help? so instead of a playbook like this,

 ---
 - name: Example
   hosts: all
   roles:
    - first_role
    - second_role
    - third_role

maybe this,

 ---
 - name: Example
   hosts: all
   tasks:
    - etckeeper_task
    - include_role:
        name: first_role
    - etckeeper_task
    - include_role:
        name: second_role
    - etckeeper_task
    - include_role:
        name: third_role
    - etckeeper_task

alternatively (also untested) you could build a role, let's call it wrap_role with tasks/main.yml containing,

---
# Replace this task with your actual before-role etckeeper task,
- name: etckeeper pre-actions
  meta: noop

- include_role:
  name: {{role_name}}

# Replace this task with your actual after-role etckeeper task,
- name: etckeeper post-actions
  meta: noop

Now your top-level playbook can be something like,

 ---
 - name: Example
   hosts: all
   roles:
     - { role: wrap_role, role_name: first_role }
     - { role: wrap_role, role_name: second_role }
     - { role: wrap_role, role_name: third_role }

not ideal based on your question, but at least it leaves the roles untouched, even if you have to alter top-level playbooks. If I get the time I'll test the above suggestions and update this answer accordingly.

1
  • Thank you for your suggestions, but as you have noted this does not solve my problem.
    – fklemp
    Sep 30 '20 at 8:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.