Ansible rpm_key Module Tutorial + Examples


Percy Grunwald's Profile Picture

Written by Percy Grunwald

— Last Updated February 22, 2019

What does the Ansible rpm_key module do?

Ansible’s rpm_key module imports a GPG public key into the local RPM GPG keyring, which is used to verify RPM packages from third party repositories. A popular example of a third party repository that uses GPG signing to verify their packages is the Elasticsearch RPM repository.

Managing RPM keys generally requires superuser/root permissions, so become: true is required in most cases.

The rpm_key module is generally used in combination with the yum module and yum_repository module:

- name: install elasticsearch rpm key
  rpm_key:
    key: https://artifacts.elastic.co/GPG-KEY-elasticsearch
    state: present
  become: true

- name: install elasticsearch 6.x rpm repository
  yum_repository:
    name: elasticsearch-6.x
    description: Elasticsearch repository for 6.x packages
    baseurl: https://artifacts.elastic.co/packages/6.x/yum
    gpgcheck: true
    gpgkey: https://artifacts.elastic.co/GPG-KEY-elasticsearch
  become: true

- name: install java & elasticsearch 6.x
  yum:
    name: "{{ item }}"
    state: present
    update_cache: true
  loop:
    - java-1.7.0-openjdk
    - elasticsearch
  become: true

Examples

How to import a GPG key from a URL

Simply set the key parameter to the URL and state: present. If they key is already installed, Ansible will do nothing. The example below shows how to import the Elasticsearch PGP key:

- name: install elasticsearch rpm key
  rpm_key:
    key: https://artifacts.elastic.co/GPG-KEY-elasticsearch
    state: present
  become: true

How to import a GPG key from a file

You can also pass a file path to the key parameter to import a GPG key from a local file. In the example below, we import the same key as above, but download it to a local file beforehand.

- name: download the elasticsearch rpm key
  get_url:
    url: https://artifacts.elastic.co/GPG-KEY-elasticsearch
    dest: /etc/elasticsearch.key
  become: true

- name: install elasticsearch rpm key from a file
  rpm_key:
    key: /etc/elasticsearch.key
    state: present
  become: true

How to remove a GPG key from the RPM keyring

Set absent: false to ensure that a key is not installed. If a key is already absent, Ansible will do nothing.

- name: remove elasticsearch rpm key
  rpm_key:
    key: https://artifacts.elastic.co/GPG-KEY-elasticsearch
    state: absent
  become: true

How to capture rpm_key module output

Use the register keyword to capture the output of the rpm_key module.

- name: install elasticsearch rpm key
  rpm_key:
    key: https://artifacts.elastic.co/GPG-KEY-elasticsearch
    state: present
  become: true
  register: rpm_key_output

The debug task above will output the following:

ok: [123.123.123.123] => {
    "rpm_key_output": {
        "changed": true,
        "failed": false
    }
}

Further reading

Comment & Share