Search code examples
ansibleinfrastructure

How to abstract roles in ansible


I have a bunch of services, which are built and deployed with ansible. Each service is managed by it's own team, has separate repository and they are completely independent from each other. I have some ansible roles that are the same in all of services (like installed packages, web servers and so on). Is there any way to abstract such roles for example in a different repository or some kind of package and include them as a dependency in another ansible role?

Example:

service-foo/
  play.yml – includes all roles
  roles/
    common – the same!
    db-foo 
    web-foo

service-bar/
  play.yml – includes all roles
  roles/
    common – the same!
    db-bar
    web-bar

I want it to look like this:

role-storage?
  common

service-foo/
  play.yml - includes common as external dependency as well
  roles/
    db-foo
    web-foo

service-bar/
  play.yml - includes common as external dependency as well
  roles/
    db-bar
    web-bar

Solution

  • It sounds like what you want to do is set up the common role as a dependency. Create the directories roles/service-foo/meta and roles/service-bar/meta and in each of those directories add a main.yml that lists the dependant role(s):

    ---
    dependencies:
        - { role: common }
    

    common is just another role stored in your roles directory. If you want to get fancy then the dependant roles can be pulled directly from github, etc. The Ansible documentation I linked to provides all the details.