ansible icon indicating copy to clipboard operation
ansible copied to clipboard

Share common tasks across roles

Open gardar opened this issue 2 years ago • 1 comments

We should investigate if it would make sense to share some of the common task files across roles, to avoid duplicate code.

For example much of the selinux.yml, install.yml, configure.yml is the same across roles.

We could collect those common task files into one role and just include the tasks we need from that role

So something like this: From: https://github.com/prometheus-community/ansible/blob/d389ad29e203ed24aebb02796958837bdca6d35e/roles/node_exporter/tasks/main.yml#L24-L31

to:

 - name: SELinux 
   ansible.builtin.include_role: 
     name: prometheus.prometheus.common
     tasks_from: selinux.yml 
     apply: 
       become: true 
   when: ansible_selinux.status == "enabled" 
   tags: 
     - node_exporter_configure 

It's also possible to pass variables to the role when it's being imported, so we can essentially use the common role to create functions which we can use across other roles. Something like:

- name: Install
  ansible.builtin.include_role:
    name: prometheus.prometheus.common
    tasks_from: install.yml
  vars:
    binary_url: https://example.tld/prometheus.tar.gz
    user: node-exp

gardar avatar Mar 09 '23 15:03 gardar

cc @SuperQ @paulfantom

gardar avatar Mar 09 '23 15:03 gardar