27 août 2018

[ANSIBLE] Best practices for sharing Ansible Roles across multiple projects

Ansible is a great tool with a lot of flexibility. It’s generally the easiest configuration management tool for new users to start with due to the batteries-included philosophy, straightforward DSL, and daemonless push model.
However, as your infrastructure goals become more complex, the flexibility means it’s less obvious how things should be structured.
For example, it’s very common to reuse the same role across multiple projects, and I’ve talked with many people who handle this by copy/pasting the role in each project. Anytime they make a change to the role, they have to remember to manually update all the projects that have copies of that role, which is tedious and error-prone.
There is a better way.™ A couple of little-known Ansible features can be combined to easily share a single role across multiple projects without duplicating code.
To do this, I stick all my shared roles in a single master folder that gets shared across all my projects. This avoids the tediousness of manual copy/pasting and updating multiple copies of the same role. If you want more granularity, this technique also supports organizing groups of roles into dedicated folders–perhaps one for roles used in work projects and one for person projects.
Than I modify each project’s  ansible.cfg to tell Ansible to look for roles in that master folder in addition to the local project folder.
Sample ansible.cfg:
Ansible first searches the local project for a role, then searches the roles_path. You can specify multiple paths by separating them with colons.
By default,  ansible-galaxy install username.rolename will install the role to the roles_path configured in ansible.cfg, so that’s pretty much all you need to do.
Occasionally I want to install the role into the specific project and not the master folder. For example, to avoid version conflicts when two roles have role dependencies that require different versions of the same role. In that case, you can use the -p ROLES_PATH or --roles-path=ROLES_PATH option:
Alternatively, in your project’s requirements.yml, you can manually specify where you want a role to be installed:
If you want to customize things further, there’s currently some discussion about Ansible 2.0 adding support for multiple ansible.cfg files which would let you easily set roles_path at varying levels of specificity. Ansible will read ANSIBLE_CONFIG, ansible.cfg in the current working directory, .ansible.cfg in the home directory or /etc/ansible/ansible.cfg, whichever it finds first.
If you want to see more examples of how I use Ansible, check out my roles on Ansible Galaxy.



Aucun commentaire:

Enregistrer un commentaire

Différences majeures entre Red Hat 6, 7, 8 et 9

Quelles sont les différences majeures entre RHEL 6, 7, 8 et 9 ? Système de fichiers RHEL 6: Par défaut : ext4. Autres : ext2, ext3 supportés...