Traps of unofficial APT Repository keys in Ansible

Learn how to automate APT repository key updates in Ansible as an example, ensuring secure and idempotent key management.

When APT Keys Expire, Updates Break

Third-party APT repositories sign their packages with a key. Docker is a common example. Those keys expire. When they do, apt upgrade fails with errors like "NO_PUBKEY" or "key expired," and package updates stop until the key is refreshed. That turns routine system maintenance into manual repair work.

This article shows how to automate the update with Ansible, using the Docker repository as the example. The result is secure, idempotent key handling with minimal manual intervention.

Where Is the Key Logic Lives

All logic for managing APT repository keys lives in one Ansible role:

  • roles/repo_keys/tasks/main.yaml — the entry point
  • roles/repo_keys/tasks/update.yaml — the update logic

The playbook calls the role; the role handles the rest.

Defining Repository Keys

Repository keys are stored as facts in a local facts file, for example located at /etc/ansible/facts.d/plr.fact. Each key entry includes:

  • Local key path: Where the key is stored locally (e.g., /etc/apt/trusted.gpg.d/docker.asc).
  • Remote key URL: The source of the key (e.g., https://download.docker.com/linux/ubuntu/gpg).

This structure allows Ansible to track and manage multiple keys systematically.

Updating Repository Keys

The update process is automated through a series of tasks in update.yaml. Here’s how it works:

a. Loop Over All Known Keys

The main task iterates over all keys defined in the local facts:

- name: Process all repository keys
  ansible.builtin.include_tasks: update.yaml
  tags: [pkg, maintenance]
  loop: "{{ hostvars[inventory_hostname].ansible_local.plr.repo_keys | default({}) | dict2items }}"

The other tasks in update.yaml are executed for each key, ensuring that all keys are processed in a single playbook run.

b. Download the Remote Key

For each key, Ansible downloads the latest version from the remote URL to a temporary location:

- name: Fetch remote repository key
  ansible.builtin.get_url:
    url: "{{ item.value }}"
    dest: "/tmp/{{ item.key | basename }}"
    mode: u=rw,g=r,o=r
  changed_when: false

c. Validate the Downloaded Key

To prevent corrupt or incomplete downloads, Ansible checks the file size:

- name: Retrieve remote key metadata
  ansible.builtin.stat:
    path: "/tmp/{{ item.key | basename }}"
  register: remote_key_file_stat

- name: Verify remote key validity
  ansible.builtin.debug:
    msg: "Remote file {{ item.value }} is invalid (size: {{ remote_key_file_stat.stat.size }} bytes)"
  when: remote_key_file_stat.stat.size < 100

d. Compare Local and Remote Keys

Ansible compares the checksum of the local key with the downloaded key:

- name: Retrieve local key metadata
  ansible.builtin.stat:
    path: "{{ item.key }}"
  register: local_key_stat

- name: Confirm local key is current
  ansible.builtin.debug:
    msg: "Local key {{ item.key }} is up to date"
  when: local_key_stat.stat.checksum == remote_key_file_stat.stat.checksum

e. Update the Local Key If Needed

If the checksums differ and the remote key is valid, Ansible updates the local key:

- name: Replace outdated local key
  become: true
  ansible.builtin.copy:
    remote_src: true
    src: "/tmp/{{ item.key | basename }}"
    dest: "{{ item.key }}"
    mode: u=rw,g=r,o=r
  when:
    - remote_key_file_stat.stat.size >= 100
    - local_key_stat.stat.checksum != remote_key_file_stat.stat.checksum

Registering New Keys as Facts

When adding a new repository, such as Docker’s, the key is registered as a fact for future updates. For example:

- name: Register Docker key as fact
  tags: [fact, pkg, maintenance]
  community.general.ini_file:
    path: "/etc/ansible/facts.d/plr.fact"
    section: repo_keys
    option: "/etc/apt/trusted.gpg.d/docker.asc"
    value: "https://download.docker.com/linux/ubuntu/gpg"
    mode: mode: u=rw,g=r,o=r
    state: present

Complete Role Code

The full role lives in two task files: main.yaml loops over the registered keys and pulls in update.yaml for each one. Fact registration happens separately in the role that installs the software, shown here for containerd.

# roles/repo_keys/tasks/main.yaml
- name: Process all repository keys
  ansible.builtin.include_tasks: update.yaml
  tags: [pkg, maintenance]
  loop: "{{ hostvars[inventory_hostname].ansible_local.plr.repo_keys | default({}) | dict2items }}"

# roles/repo_keys/tasks/update.yaml
- name: Fetch remote repository key
  ansible.builtin.get_url:
    url: "{{ item.value }}"
    dest: "/tmp/{{ item.key | basename }}"
    mode: u=rw,g=r,o=r
  changed_when: false

- name: Retrieve remote key metadata
  ansible.builtin.stat:
    path: "/tmp/{{ item.key | basename }}"
  register: remote_key_file_stat

- name: Verify remote key validity
  ansible.builtin.debug:
    msg: "Remote file {{ item.value }} is invalid (size: {{ remote_key_file_stat.stat.size }} bytes)"
  when: remote_key_file_stat.stat.size < 100

- name: Retrieve local key metadata
  ansible.builtin.stat:
    path: "{{ item.key }}"
  register: local_key_stat

- name: Confirm local key is current
  ansible.builtin.debug:
    msg: "Local key {{ item.key }} is up to date"
  when: local_key_stat.stat.checksum == remote_key_file_stat.stat.checksum

- name: Replace outdated local key
  become: true
  ansible.builtin.copy:
    remote_src: true
    src: "/tmp/{{ item.key | basename }}"
    dest: "{{ item.key }}"
    mode: u=rw,g=r,o=r
  when:
    - remote_key_file_stat.stat.size >= 100
    - local_key_stat.stat.checksum != remote_key_file_stat.stat.checksum

# Example fact registration (e.g., in roles/containerd/tasks/main.yml)
- name: Register Docker key as fact
  tags: [fact, pkg, maintenance]
  community.general.ini_file:
    path: "/etc/ansible/facts.d/plr.fact"
    section: repo_keys
    option: "/etc/apt/trusted.gpg.d/docker.asc"
    value: "https://download.docker.com/linux/ubuntu/gpg"
    mode: u=rw,g=r,o=r
    state: present

Summary of the Process

Step Description
Define keys Store key path and URL as facts
Loop over keys Process each key in the facts file
Download remote key Fetch the latest key from the remote URL
Validate key Ensure the downloaded key is not corrupt
Compare checksums Check if the local key matches the remote key
Update if needed Replace the local key if it differs

Tips That Make the Role Solid

  • Do only what is needed. The role checks checksums first. It updates a key only when the file has changed.
  • Catch bad downloads early. A file size check stops corrupt keys from being installed.
  • Let the loop do the work. The role reads its facts and handles any number of keys with no extra code.
  • Limit root access. Only the tasks that need it use become: true.

Extending the System

To add a new repository key (e.g., for a different repository), register it as a fact using the ini_file module, as shown above. The update logic will automatically include it in future runs, making the system highly extensible.