ansible apt-key module with loop

668 Views Asked by At

I'm provisioning a system that requires multiple GPG keys to be added. I'm attempting to streamline the process and follow DRY principals.

I have apt packages installing from a vars list like so:

- name: Install packages
  apt: name={{ apt_packages }}

Where my vars.yml looks like this:

apt_packages:
  - tilix
  - terraform
  - ansible
  - opera

This works because the apt module accepts comma separated inputs and parses accordingly.

So I'm trying to achieve a similar process when using the apt_key module but I can't seem to get it to work. Here are a couple of attempts I've made:

- name Add keys
  apt_key:
    url: url="{{ items }}"
    loop: "{{ gpg_keys }}"
    state: present

and

- name: Add GPG Keys
  apt_key:
    url: url="{{ gpg_keys }}"
    state: present

Both throw different errors.

Is it possible to do something like this using the apt-key module? Obviously I'm trying to avoid having a separate caller for each key I want to add as there will be many keys and I'd like to be able to add additional keys later on by simply appending the list in vars.yml.

1

There are 1 best solutions below

1
On BEST ANSWER

You have a few small mistakes in your task.
The right way is this:

- name: Add keys
  apt_key:
    url: "{{ item }}"
    state: present
  loop: "{{ gpg_keys }}"
  • you already have the key url, so prepending url= is incorrect
  • loop is an argument to the task and not to the apt_key module, so it needs to be indented to the level of apt_key (unlike url which is an argument to the model)

Sidenotes:

  • You also need to make sure that gpg_keys contains a list, similar to apt_packages.
  • The name parameter of apt accepts a list, as you define correctly in your vars.yml, no comma-separated string. (You are already doing it right)

Documentation: