I have a couple of roles that add files to sources.list.d, and then install packages. Is it somehow possible to run the apt module to update apt index after ALL roles have added the files but before installing packages? I have tried a few approaches, none seems ideal:
Not making roles adding sources.list file, but instead put them in a central folder and use pre_tasks to add files and run apt before running roles.
This means if a role is not included, the corresponding sources.list file is still added.
Split each role into two roles, where one is for adding sources.list, the other installing packages.
With this approach, I use two loops, each in a separate playbook task, where the first loop includes roles that add sources.list files, and then apt module is run, and finally the second loop includes roles that install packages.
This forces me to explicitly list all roles needed (including dependencies) in a variable.
I wonder if there exist an elegant solution to run apt only once for all roles?
You could register the result of the file adding in each role, to a variable.
At the end you use that to decide if an apt task should be run that updates the cache.
At the end you use that to decide if an apt task should be run that updates the cache.
I wonder where the “end” should be? Since each role’s tasks contain both adding the sources.list and installing packages. It seems a task at the playbook can only either update the apt cache before all addings or after all installings.
If that is the case (each of the roles adds a sources.list.d file, and install packages), then I don't think this is possible, as the roles are run sequentially.
I would then change each role to conditionally do 'apt-get update' depending on whether a file was dropped in /etc/apt/sources.list.d.
But, adding files to /etc/apt/sources.list.d sounds like a legacy approach. Perhaps this is already old code?
Ideally you'd just use a single apt_repository task, which has a conditional update_cache option built-in: