Ansible Roles

I consider a role to be a reusable, (mostly) standalone component to be consumed within a playbook. For instance, we have several different tools which require JDK, so we have a single role called install-oracle-jdk which downloads the JDK, installs it, updates the cacerts with some of our internal certificates, and makes sure that Java is available in the path for all users.

In the most simple case, a role is broken down like this:

.
__roles/
  |__role-name/
    |__tasks/
      |__main.yml
    |__vars/
      |__main.yml

In side of the role-name directory are two directories, the tasks/ directory and the vars/ directory. Inside of those two directories is a file called main.yml. vars/main.yml contains the default values of the variables needed for a given role and tasks/main.yml contains the steps required to apply that role. The intent is that if a role is run within a playbook without any variables overridden (more on that later), it will use the default variables. For a role like install-oracle-jdk, there might be a need to specify a different version of JDK. The other benefit of this approach is that when we’ve gone from 8_181 to 8_191 to 8_201 (current at time of writing), we only need to change it in one place and the next time we run the playbook, we’re able to confirm that the same/latest version of Java is installed across all machines in the inventory file which consume that role.

We have other roles where we’d need to pipe in additional variables. When executing a playbook, we generally use the a defaults file which we keep up in the top level directory of our Ansible repository. In the next post, I’ll cover how/when/why we use these defaults files.

 

Leave a Reply

Your email address will not be published. Required fields are marked *