Ansible when apt repository?
Ansible’s apt_repository module is used to manage repositories for the apt package manager. The most common use case for this module is adding a third party repository, such as Elasticsearch.
Before adding a repository with this module, you will usually need to add a GPG key with the apt_key module as shown in the examples below.
Superuser (root) privileges are usually required to manage apt keys and repositories, so become: true should be used in most cases.
The apt_repository module is generally used in combination with the apt module and apt_key module:
This module is only relevant for Debian-based Linux distributions such as Debian and Ubuntu. For Red Hat-based distros such as Red Hat Enterprise Linux and CentOS, use the corresponding yum modules to manage keys and repositories, and install packages:
The example below adapts the installation instructions for installing Elasticsearch with apt into Ansible form.
Packages from Elastic are signed with their GPG key, so we should import the key with the apt_key module:
The instructions call for creating a file in /etc/apt/sources.list.d/; this is what the apt_repository module will do automatically. Set the repo parameter to the repo string, which is usually in the form deb {{ repo_url }} stable main.
Now that the elasticsearch-6.x repo has been added, we can install the elasticsearch package with the apt module. apt will search all available repositories to look for the elasticsearch package and install it if not already installed.
Java is a prerequisite for elasticsearch and must be fully installed before attempting to install elasticsearch. Using the loop keyword rather than passing the list to name means that the command below will install openjdk-8-jre-headless before attempting to install elasticsearch:
Removing an apt repository is as simple as setting the repo parameter and setting state: absent.
Use the register keyword to capture the output of the apt_repository module.
The debug task above will output the following:
- update_cache=yes – Run the equivalent of apt-get update command on all servers.
- force_apt_get=yes – Do not use the aptitude command, instead use the apt-get command on Debian/Ubuntu boxes.
- cache_valid_time=3600 – Update the apt cache if its older than the cache_valid_time.