What are Ansible Collections?
Ansible is an infrastructure as code tool used for configuration management, network device management, orchestration and other tasks. Ansible Collections are a way to distribute Ansible content such as roles, playbooks and modules. They can be downloaded from Ansible Galaxy, Git repositories or local directories. Basically collections are a more modern packaging format compared to standalone roles which they are in the process of replacing. Version-locking Ansible Collections allows you to run the exact same Ansible code every time.
Version locking Ansible Collections
When you use collections it makes a lot of sense to version-lock them, even though that is not really emphasized in the official documentation. If you don't version-lock dependencies such as collections or roles, you have no guarantees that your code will behave the same each and every time. When your Ansible is bootstrapped by someone he or she could get completely different dependency versions than somebody else. This, in turn, will eventually cause problems when your own playbooks or roles are incompatible with the collections they depend on.
Version locking Ansible collections on the project level ensures that everybody uses the exact same Ansible code, including your local code and its dependencies . Version locking also allows controlling the changes going into project dependencies.
Configuring project-specific collections in Ansible
The first step is to create an Ansible configuration file, ansible.cfg, to the root of your project:
[defaults] collections_paths = ./collections
This tells Ansible to look for collections in the current directory under collections subdirectory. The next step is to create a collections/requirements.yml file which tells which dependencies your project needs. While requirements.yml can be placed anywhere, the above location is the only one that is compatible with Ansible Tower. Here's a minimal example for version locking Ansible Collections:
--- collections: - name: https://github.com/Puppet-Finland/ansible-collections-puppeteers-keycloak.git type: git version: 1.0.1
For details on the requirements.yml syntax please refer to the official documentation.
Note that if any of the collections you list has collection dependencies of their own, those will also be installed automatically. This means there's a fair chance of a "dependency hell" as your requirements.yml file grows and the requirements of different collections become impossible to satisfy at the same time.
To install the collections run this command:
ansible-galaxy collection install -r collections/requirements.yml
You should also add ansible_collections to .gitignore, like this:
That way you don't accidentally version your external dependencies.